-
I have got this API that allows me to edit and list snippets:
Based on Let's suppose I am showing the snippets returned by (a) in a list: const {data: snippets} = useSWR("/snippets/");
// show snippets in list And that each snippet has a button to edit const handleClickExclude = async (snippetId) => {
await axios.patch(`/snippets/${snippetId}/`, {include: false})
mutate("/snippets/", cached => cached.filter(snippet => snippet.id != snippetId) ); // (1)
};
<Snippet onClick={() => handleClickExclude(snippet.id)}/> If I mutate on (1) also updating the cache, the snippets list gets updated, but only after the patch is finished and this does not feel instantaneous like optimistic updates should be. On the other end, if I move (1) one line up, the revalidation of How I fixed thisI guess we need a way to mutate the cache without triggering the revalidation immediately for these optimistic update cases. I came up with an hook for these situations. export default function useMutableSWR(key) {
const swr = useSWR(key);
const [data, setData] = useState(swr.data);
useEffect(() => {
setData(swr.data);
}, [swr.data]);
return { ...swr, data, setData };
} It works exactly as const {data: snippets, setData: setSnippets} = useSWR("/snippets/");
// ...
const handleClickExclude = async (snippetId) => {
setSnippets(snippets.filter(snippet => snippet.id !== snippedId));
await axios.patch(`/snippets/${snippetId}/`, {include: false});
mutate("/snippets/");
}; My QuestionIs there a better way to handle this with the library itself? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I hope this example could help |
Beta Was this translation helpful? Give feedback.
-
It helped, thanks. For anyone stumbling into this, the solution is to do use one of the parameters of |
Beta Was this translation helpful? Give feedback.
It helped, thanks. For anyone stumbling into this, the solution is to do use one of the parameters of
mutate
, the last one, which defines wether to revalidate or not.mutate(key, value, false)
, changes the value in the cache, without triggering a revalidation with the server, so avoiding all problems I outlined above.