Cannot use global mutate with useSWRInfinite
See original GitHub issueBug report
Description / Observed Behavior
There is no way to mutate data fetched with useSWRInfinite
without first fetching the data client-side. I saw this answer by @shuding and it definitely works, but it triggers a fetch when all I want to do is mutate data (if it has already been fetched).
Expected Behavior
Instead, I should be able to mutate local data without triggering a fetch. The global mutate
function should allow me to mutate data that has already been fetched (e.g. on a page that uses useSWRInfinite
) on a page that should not trigger a fetch of that data.
My (pretty common I think) use-case:
- I have a list of emails fetched using
useSWRInfinite
on a/feed
page. - When the user opens an email, they can modify it on a
/messages/[id]
page. - I want to mutate the data shown on the
/feed
page when the data is edited on the/messages/[id]
page.
But, the user can also open the /messages/[id]
page directly, in which case the /feed
page will never have been opened and useSWRInfinite
will never have been called. In this case, I don’t want to trigger a fetch with useSWRInfinite
.
Repro Steps / Code Example
This is the project I’m working on: nicholaschiang/hammock
.
Additional Context
SWR version: 0.5.5 Related to #435.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:11
- Comments:7 (2 by maintainers)
I’m not sure if it’s a good idea to expose internal implementation details (things like
inf
), as they will likely to change over time. The idea of #1174 is to support use cases likemutate(regex)
ormutate(filterFn)
in the future.While
useSWRInfinite
is a truly special case, I’d propose amutateInfinite
method so you can domutateInfinite(KEY_FOR_FIRST_PAGE)
ormutateInfinite(getKey)
. It basically hides theinf
inside.A solution in https://github.com/vercel/swr/issues/1156#issuecomment-845264050 might work at this time, but it would be broken in the future. For example, https://github.com/vercel/swr/pull/1174 breaks your solution. I think SWR should provide a solution to generate the key, which doesn’t depend on the internal implementation if there is any valid use-case that the global
mutate
has to use.