react query optimistic update "old is not iterable" why this error occured

Viewed 98

Updating profile is working fine, but optimistic update is not working properly. An error occured 'old is not iterable'. How to fix this ?

  export const useUpdateProfile = () => {
  const queryClient = useQueryClient();

  return useMutation(updateProfile, {
    onMutate: async (newProfile) => {
      // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
      await queryClient.cancelQueries("user-profile");
      // Snapshot the previous value
      const previousProfile = queryClient.getQueryData("user-profile");

      // Optimistically update to the new value
      queryClient.setQueryData(["user-profile"], (old) => [...old, newProfile]);

      // Return a context object with the snapshotted value
      return { previousTodos };
    },
    // If the mutation fails, use the context returned from onMutate to roll back
    onError: (err, newTodo, context) => {
      queryClient.setQueryData("user-profile", context.previousProfile);
    },
    // Always refetch after error or success:
    onSettled: () => {
      queryClient.invalidateQueries("user-profile");
    },
  });
};
1 Answers

it seems that the getting the user-profile gives you back undefined, potentially because it doesn't exist? Make sure to check for undefined before spreading:

// Optimistically update to the new value
queryClient.setQueryData(["user-profile"], (old) => old ? [...old, newProfile] : []);

if you've upgraded to v4 (@tanstack/react-query) already, you can also return undefined from the updater to bail out of the update:

queryClient.setQueryData(["user-profile"], (old) => old ? [...old, newProfile] : undefined);
Related