Support `populateCache` as a function
See original GitHub issueWe added the populateCache
option (as well as other options for optimistic UI) recently, a normal use case looks like the following:
mutate(addTodo(todo), {
optimisticData: [...todos, todo],
populateCache: true,
rollbackOnError: true,
revalidate: false,
})
Say that the addTodo
calls the POST /api/todos
endpoint, which returns the full, updated list.
Transform Before Populating the Cache
However, it’s also common that the POST /api/todos
endpoint only returns the new added item, not the full list. So naturally the next step is to support populateCache
as a synchronous function that transforms the returned data before writing back to the cache:
mutate(addTodo(todo), {
optimisticData: [...todos, todo],
populateCache: addedTodo => [...todos, addedTodo],
rollbackOnError: true,
revalidate: true,
})
Note that revalidate: true
is needed now.
Also populateCache
is synchronous only to avoid possible race conditions.
Opt-out
With this design, if an error is throw when calling populateCache
, we can skip populating the cache for this specific mutation.
This enables a way to conditionally populating the cache.
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (4 by maintainers)
I think then the
populateCache
option needs to accept the current data as well, something like:So this can be wrapped in an event callback which is totally pure and doesn’t depend on the hook state.
Thanks for your answers, I just added a feature request in the Discussion of the repository (https://github.com/vercel/swr/discussions/1850)