swr: global mutate can't revalidate useSWRInfinite data
Bug report
Description / Observed Behavior
What kind of issues did you encounter with SWR?
For example a Todo app, on the list page:
I using useSWRInfinite to load todos, the first page’s key is /api/todos,
Then I delete a Todo (send request to backend to deleted it), and I need revalidate the data:
If I use mutate returned from the useSWRInfinite call, it will work.
If I use mutate from const { mutate } = useSWRConfig(), it will not work.
Expected Behavior
How did you expect SWR to behave here?
Both way need way. because I may call the delete not on the same component, so I can’t pass the mutate function to other component
Repro Steps / Code Example
Additional Context
SWR version. 1.0.1
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 1
- Comments: 15 (4 by maintainers)
I just found a workaround for this problem. The filter key will not work with the infinite swr, so I just iterate the cache hash map keys and call the mutate for the key I want.
The code that doesn’t work:
To this:
Note that with this code you can accidentally revalidate unwanted routes. so you can make a better comparison than “includes”. But in my case worked really well.
I’ve just made my own mutation hook to handle this problem.
Usage:
I suggest this be reopened.
We should add this to the docs, but there is currently a bug in Nextra blocking this…
@Lexizz7 I’ve tried your idea, and it kind of works, but I have to call
mutatetwice to trigger the network request (and refresh the component). Similar to what @nielskrijger wrote. But I can’t simply userevalidateAll: true.Do you perhaps know why it might not work as expected?
You could use
unstable_serializeto get the keys of swr infiniteI tried @Lexizz7 approach and had some weird behaviour… Basically every other time it worked;
mutate()it didn’t refreshmutate()it does refreshChanging
revalidateAll: false -> truemade it work every time.No idea why that works, it was only loading a single page.
Can I ask what the reason is for the prefix? I’m using
useSWRInfiniteas a workaround for needing to make a dynamic number ofuseSWRcalls and this difference has caused some bugs in my application.@ezeikel Good point! I opened https://github.com/vercel/swr-site/issues/264 for this doc requirement
Not sure why this was closed? Would be great if this issue was still open and the docs got updated to reflect this
I checked code, there is a
const INFINITE_PREFIX = '$inf$'added to the key when using infinite, so I try use global mutate, and call,mutate('$inf$/api/todos'), and it work.