swr
swr copied to clipboard
Optimistic update with useSWRMutation
Bug report
Description / Observed Behavior
I'm trying to implement an optimistic update with useSWRMutation.
For some reason the data doesn't change optimistically. It is waiting for the fetcher resolve and then changes.
optimisticData is called, but it doesn't do anything.
Expected Behavior
Please see the attached example.
data should change rightaway to true when the button is clicked, but it is still undefined until the promise resolves.
Repro Steps / Code Example
https://codesandbox.io/p/sandbox/hopeful-bouman-cr27yt
Additional Context
SWR version: 2.2.5. Add any other context about the problem here.
Same problem here! Did you find any solution?
Hi! No, unfortunately I don't have any news
Can't you use const { mutate } = useSWRConfig(); ? or perhaps Reacts useOptimistic, startTransition ?
I use these in combination with useSWR to do optimistic changes instanly clientside without waiting for the server to finish mutating and revalidating the tag
Yeah, the data returned from useSWRMutation is the same as the return value of mutate, which means the value doesn't respect optimisticData.
(This might be confusing)
You can get the data applied optimisticData with useSWR` like this.
// get data from `useSWR`
const { data, error } = useSWR("toggle-floating-mode", fetcher);
https://codesandbox.io/p/sandbox/hopeful-bouman-forked-9kx2l5
Thank you @koba04. I could solve the problem thanks to you. I appreciate your nice work :smile:
But the sandbox you provided has an No Overload Matches this call error at the second argument of useSWR.
You could remove the second argument just like the following source code, then everything goes well.
const { data, error } = useSWR("toggle-floating-mode");