Is it safe to mutate query data in the setQueryData function? Or do I always need to be creating new objects? #4962
-
Coming from redux of five or so years ago, it was ingrained in me not to mutate objects directing in your reducer functions, instead you should always be returning objects. This has changed with RTK now using Immer. So question is, say I'm doing an optimistic update on my list of todos, like: const qc = useQueryClient();
const mutation = useMutation({
//snip
onSuccess: (newData) => {
qc.setQueryData(["todos"], (oldData) => {
//??? Question here
});
});
}) Is it safe for me to do oldData.push(newData);
return oldData; Or do I need to be doing return [...oldData, newData] ? Appreciate a link to the relevant docs if this is clarified somewhere. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
It does look like the 'create new objects' approach is being used in the example given here. |
Beta Was this translation helpful? Give feedback.
-
Hi 👋 No, this is not safe. It might work but can lead to subtle bugs, similar to mutable React state updates. Cache updates must be made immutably. Please see: https://tanstack.com/query/v4/docs/react/guides/updates-from-mutation-responses#immutability |
Beta Was this translation helpful? Give feedback.
Hi 👋
No, this is not safe. It might work but can lead to subtle bugs, similar to mutable React state updates. Cache updates must be made immutably.
Please see: https://tanstack.com/query/v4/docs/react/guides/updates-from-mutation-responses#immutability