useMutation - updating a single entry in onMutate
I am trying to follow the tutorial on tanstack for doing optimistic updates. I cannot make their example work in my app for updating a single entry in the onMutate function. I am following the guide here: https://tanstack.com/query/latest/docs/framework/react/guides/optimistic-updates for "Updating a single todo".
Optimistic Updates | TanStack Query Docs
React Query provides two ways to optimistically update your UI before a mutation has completed. You can either use the onMutate option to update your cache directly, or leverage the returned variables to update your UI from the useMutation result.
Via the UI
5 Replies
graceful-blueOP•2y ago
In their code, they have this line of code:
queryClient.setQueryData(['todos', newTodo.id], newTodo)
.other-emerald•2y ago
okay but the guide is fine, so ... share some code? Your own codesandbox reproduction would be best
graceful-blueOP•2y ago
and this is mine:
my understanding is that
setQueryData
call will update the chemicals state array entry at the given id with correctUpdatedChemical
I know when i did something like this it worked, prev => prev.map(c => c.id === correctUpdatedChemical.id ? correctUpdatedChemical : c)}
other-emerald•2y ago
are you writing to a cache entry that contains an array or that just contains a single object? Sorry this is just easier to understand if you do the work and provide a sandbox
graceful-blueOP•2y ago
I can try the sandbox, its a fairly big project. This is my 'get' function in the same component:
but that is then passed down a couple components to be displayed in a table
oh wait
your question about "writing to a cache array" didn't make sense to me but then I did remember something
I have this in the same component:
that is what is getting passed down to the table component
and that is not state so I assume is not updating
I am converting the field names to id and category so I can use them in my generic
SimpleCategoriesTable
component.
I should just figure out how to change them right away in the get function and stop dealing with multiple arrays.