T
TanStack3y ago
absent-sapphire

useQuery is not refreshing data after setQueryData

Hello, why below snippet does not refresh useQuery which has queryKey equal to QueryKey.MyItems? As I log data from getQueryData, I see it's updated.
const { mutate: removeItem, isLoading } = useMutation(
[QueryKey.RemoveFromMyLibrary],
removeItemFromLibrary,
{
onSuccess: itemId => {
const previousData = queryClient.getQueryData([QueryKey.MyItems]) as GetItemsResponse
queryClient.setQueryData(..., {...data, count: data.count - 1, items: items.filter(...)})

const newData = previousData
console.log(newData, 'newData')
newData.total -= 1
const itemIndex = newData.items.findIndex(item => item.id === itemId)
newData.items.splice(itemIndex, 1)

queryClient.setQueryData([QueryKey.MyItems], newData)
const updatedData = queryClient.getQueryData([QueryKey.MyItems])
console.log(updatedData, 'updatedData')
}
}
)
const { mutate: removeItem, isLoading } = useMutation(
[QueryKey.RemoveFromMyLibrary],
removeItemFromLibrary,
{
onSuccess: itemId => {
const previousData = queryClient.getQueryData([QueryKey.MyItems]) as GetItemsResponse
queryClient.setQueryData(..., {...data, count: data.count - 1, items: items.filter(...)})

const newData = previousData
console.log(newData, 'newData')
newData.total -= 1
const itemIndex = newData.items.findIndex(item => item.id === itemId)
newData.items.splice(itemIndex, 1)

queryClient.setQueryData([QueryKey.MyItems], newData)
const updatedData = queryClient.getQueryData([QueryKey.MyItems])
console.log(updatedData, 'updatedData')
}
}
)
2 Replies
conscious-sapphire
conscious-sapphire3y ago
newData.items.splice(itemIndex, 1)
updates need to happen in an immutable way https://tanstack.com/query/v4/docs/react/guides/updates-from-mutation-responses#immutability
Updates from Mutation Responses | TanStack Query Docs
When dealing with mutations that update objects on the server, it's common for the new object to be automatically returned in the response of the mutation. Instead of refetching any queries for that item and wasting a network call for data we already have, we can take advantage of the object returned by the mutation function and update the exis...
absent-sapphire
absent-sapphireOP3y ago
thank you, that's it

Did you find this page helpful?