TanStackT
TanStack3y ago
4 replies
broad-emerald

Set query data not working for optimistic updates

I'm using a mutation to add a question to a list of questions and I'd like to implement optimistic updates like in this guide (https://tanstack.com/query/v4/docs/react/guides/optimistic-updates).
My current mutation looks like this:
const mutation = useMutation({
  mutationFn: createNodeMutation,
  onMutate: async (values) => {
    await queryClient.cancelQueries({
      queryKey: [QueryKeys.NODES, me.tenantId],
    });
    const previousNodes = queryClient.getQueryData([
      QueryKeys.NODES,
      me.tenantId,
    ]);
    queryClient.setQueryData([QueryKeys.NODES, me.tenantId], (oldNodes) => [
      ...oldNodes,
      values,
    ]);
    return { previousNodes };
  },
  onError: (_error, _values, context) => {
    queryClient.setQueryData(
      [QueryKeys.NODES, me.tenantId],
      context.previousNodes,
    );
  },
  onSettled: () => {
    queryClient.invalidateQueries({
      queryKey: [QueryKeys.NODES, me.tenantId],
    });
    // await new Promise((resolve) => setTimeout(resolve, 500));
  },
  onSuccess: () => {
    router.push(Routes.SITE.HOME);
  },
});

The problem is that when I try to post a new question I get this error: oldNodes is undefined.
I'm also getting this Typescript error: Type 'unknown' must have a '[Symbol.iterator]()' method that returns an iterator..
Finally, if I remove this line and put it back after posting a question, it works fine so it looks like it's not working only the first time because the oldNodes is undefined even though there already are questions present in the app so oldNodes should not be undefined.
What did I do wrong and what should I modify ?
TanStack Query (FKA React Query) is often described as the missing data-fetching library for web applications, but in more technical terms, it makes fetching, caching, synchronizing and updating server state in your web applications a breeze.

Motivation
Overview | TanStack Query Docs
Was this page helpful?