T
TanStack•14mo ago
genetic-orange

Why is prevData undefined in my onSuccess of my mutation?

I am finishing up functionity to insert a new price list into my database. Everything is working well, now on success I want to update the list of price lists on the page with the new price list. But for some reason, my console is saying prevData is undefined. This isn't the first time I've used this library, so I'm baffled. Here is my full useMutation function:
const {mutateAsync: insertPriceListMutation} = useMutation({
mutationFn: insertPriceList,
onSuccess: async (data) => {
console.log({data});
queryClient.setQueryData(['priceLists'], (prevData: any) => [
...prevData,
data.priceList
]);
setOpenEditPriceListModal(false);
await highlightNewRow(data.priceList.id);
},
onError: (error) => {
// const message = error;
toast.error(error, {
position: 'top-center',
autoClose: 4000,
containerId: 'user-modal-alert'
});
if (error.toString().includes('Name')) {
setInvalidFields([...invalidFields, 'name']);
}
}
});
const {mutateAsync: insertPriceListMutation} = useMutation({
mutationFn: insertPriceList,
onSuccess: async (data) => {
console.log({data});
queryClient.setQueryData(['priceLists'], (prevData: any) => [
...prevData,
data.priceList
]);
setOpenEditPriceListModal(false);
await highlightNewRow(data.priceList.id);
},
onError: (error) => {
// const message = error;
toast.error(error, {
position: 'top-center',
autoClose: 4000,
containerId: 'user-modal-alert'
});
if (error.toString().includes('Name')) {
setInvalidFields([...invalidFields, 'name']);
}
}
});
4 Replies
subsequent-cyan
subsequent-cyan•14mo ago
it means there is no data in the cache for a key ['priceLists']. Have you checked the react-query-devtools ?
genetic-orange
genetic-orangeOP•14mo ago
Oh no, is that a special addon or built right into devtools? nm, found it is a npm package to install, i will try that out
subsequent-cyan
subsequent-cyan•14mo ago
how do you work without the devtools 😂
genetic-orange
genetic-orangeOP•14mo ago
hah, I never even knew react-query-devtools was a thing! 🙂 ok, so that helped a lot. I see that the priceLists cache seems to be getting blown away as soon as the page loads. I've commented out almost all the code on my page and its still happening. If I console out priceLists, I can see them. Holy crap, I just figured it out!! Hopefully its ok if I tag you here, @TkDodo 🔮 . I searched this forum for why my data wasn't showing up in react-query-devtools and I found your answer here: https://discord.com/channels/719702312431386674/1059720083645141042/1059857786713931856 about the query client not being stable. Sure enough, my query client was set up inside the app component. Moved it above like in your example and BOOM! It is now working!! That feels so good!! 🙂

Did you find this page helpful?