TanStackT
TanStack3y ago
13 replies
precious-lavender

How to access previous data of query?

Someone that knows any best practices regarding how to manage optimistic updates and query cache with Tanstack Query?

I have a mutation and onSuccess of that mutation I trigger a function called updateQueryStateOnSuccess. (Where I want to update the cache for a certain query directly so I don't have to wait for it to be updated next time I fetch it)

My prevData is always undefined currently which is my main issue.

const useUpdateUserInfo = createMutation({
  request: updateUserInfo,
  dependentQueries: ['getUserInfo'],
  updateQueryStateOnSuccess: (queryClient, data, variables) => {
    queryClient.setQueryData<UserInfo>(['getUserInfo'], (prevData): UserInfo | undefined => {
      console.log('prevData: ', prevData); // Undefined even if there is data in the queryCache for that queryKey

      // const cache = queryClient.getQueryCache();
      // console.log('cache: ', cache);
      // const oldData = cache?.queriesMap?.['getUserInfo']?.state?.data?.result;
      // console.log('oldData: ', oldData); // Works but ugly af

      if (!prevData || !variables) {
        return;
      }

      console.log('updating cache');
      return {
        ...prevData,
        firstName: variables.firstName,
        lastName: variables.lastName,
        email: variables.emailId,
        phoneNumber: variables.mobileNumber,
      };
    });

  },
});
Was this page helpful?