swr icon indicating copy to clipboard operation
swr copied to clipboard

[Docs] mutate docs are outdated/incomplete

Open MonstraG opened this issue 2 years ago • 5 comments

Just as an example, the only mentions of optimisticData are

 const options = { optimisticData: user, rollbackOnError: true }

and

optimisticData: data to immediately update the client cache, usually used in optimistic UI.

only from the issues on github I can find out that it actually accepts a function.

Additionally, I find this extremely confusing that I can some kind of data updating function thrice

const {muate} = useSWR():

mutate(here, {
    populateCache: here
    optimisticData: here;
}

Finally, I can't seem to combine all of the numerous options of using mutate to achieve the following:

  1. update what's in cache with new version
  2. actual network call is not awaited and it's results are ignored

As this is, pratically, a big question, this might be better suited to be a discussion, but I wanna file this as an issue to promote improvement of docs, as I still find them lacking in other areas too (for example, stale is actually not defined, so I don't know what revalidateIfStale does)

MonstraG avatar May 13 '22 20:05 MonstraG

You can achieve that by:

mutate(request, {
  populateCache: false,
  optimisticData: currentData => newData,
  revalidate: false
}

shuding avatar May 14 '22 23:05 shuding

You can achieve that by:

mutate(request, {
  populateCache: false,
  optimisticData: currentData => newData,
  revalidate: false
}

Sadly, this doens't work in 2 ways:

  • types expect requst to return data (T | Promise<T>), which I do not want/need
  • the changes made in currentData => newData do not get re-rendered to be dispalyed in the UI.

If that makes a difference, I have a refreshInterval: 15000, on the useSWR hook from which mutate comes from.

MonstraG avatar May 16 '22 06:05 MonstraG

Thanks, and these are great feedback, I will think about how to get these cases covered.

shuding avatar May 16 '22 14:05 shuding

the changes made in currentData => newData do not get re-rendered to be dispalyed in the UI.

For this case, I just tested and SWR correctly prevents the race condition. Could you make a reproduction with this template: https://codesandbox.io/s/swr-basic-p7dg6 ?

shuding avatar May 16 '22 15:05 shuding

Found why it didn't work. After an hour remembered that useSWR uses deep comparison.

For the return type, this works:

() => {
  void postStuffToTheApi();
  return null;
},

(only because T is object, and null works here)

MonstraG avatar May 16 '22 18:05 MonstraG