I have a custom hook that looks something like this:
export const useDeleteAccount = () => {
const queryClient = useQueryClient();
const result = useMutation(
async (accountId: any) => {
...
},
{
onSuccess: async (data: { account: any; response: boolean }) => {
await queryClient.cancelQueries(accountsKey);
const previousAccounts = queryClient.getQueryData<any[]>(accountsKey) || [];
const index = previousAccounts?.findIndex(account => data.account.id === account.id);
if (index?.toString() && previousAccounts) {
if (previousAccounts && previousAccounts[index]) {
previousAccounts.splice(index, 1);
}
}
queryClient.setQueryData<any[]>(accountsKey, [...previousAccounts]);
},
}
);
return result;
};
I am deleting account from backend and then deleting it from the cache data and updating in the cache using below line
// [...previousAccounts] copy is created here
queryClient.setQueryData<any[]>(accountsKey, [...previousAccounts]);
Now here above line does not work and does not update the cache. However if I make following change then it works.
let previousAccounts = queryClient.getQueryData<any[]>(accountsKey) || [];
// copy is created here
previousAccounts = [...previousAccounts];
... logic to delete account
queryClient.setQueryData<any[]>(accountsKey, previousAccounts);
So, in above code I am first creating the copy and then deleting the account from copy and then passing that copy to setQueryData. Then it works.
Now, first code used to work in react query v3 but not in v4. In v4 my second approach is working where i create copy first.
Any idea why such behavior in react query v4?