swr icon indicating copy to clipboard operation
swr copied to clipboard

Optimistic update with useSWRMutation

Open thebat93 opened this issue 1 year ago • 5 comments

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.

thebat93 avatar Mar 27 '24 10:03 thebat93

Same problem here! Did you find any solution?

MoSattler avatar Apr 20 '24 11:04 MoSattler

Hi! No, unfortunately I don't have any news

thebat93 avatar Apr 21 '24 19:04 thebat93

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

ElectricCodeGuy avatar May 27 '24 00:05 ElectricCodeGuy

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

koba04 avatar Jun 02 '24 15:06 koba04

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");

Key5n avatar Sep 09 '24 13:09 Key5n