wyc
wyc

Reputation: 55283

useMutation not updating the useQuery data (Tanstack Query)

I following the official Tanstack Query useMutation docs to update my products after adding a new product:

ProductsPage.tsx

const { data, isError, isPending, error } = useQuery<
  FetchResponse<'products'>,
  Error
>({ queryKey: ['products'], queryFn: fetchProductsMock });

useEffect(() => {
  console.log('useEffect data:', data);
  if (data?.products) {
    setProducts(data?.products);
  }
}, [data]);

addProductModal.tsx

const queryClient = useQueryClient();

const mutation = useMutation({
  mutationFn: createProductMock,
  onSuccess: (data) => {
    console.log('useMutation data:', data);
    queryClient.setQueryData<StringRecord[]>(
      ['products'],
      (oldProducts = []) => {
        return [...oldProducts, data];
      },
    );
  },
});

function handleSubmit(values: any) {
  mutation.mutate(values);
  form.reset();
  setIsOpen(false);
}

console.log('useMutation data:', data); logs the new data, so I know the useMutation part was successful. However, console.log('useEffect data:', data); doesn't log anything, so I know useQuery didn't run again with the new data.

Am I doing something wrong?

Upvotes: 2

Views: 1065

Answers (1)

Oki
Oki

Reputation: 3240

Not sure if this is the problem, but what I see in first place is that you update your cache incorrectly. Your useQuery returns an object that has products property and your setQueryData returns an array. It should be same as the return type of the useQuery (object)

queryClient.setQueryData<StringRecord[]>(
  ['products'],
  (oldData) => {
    if (!oldData) return
    return {...oldData, products: [...oldData.products, data]};
  },
);

is the component that uses your useQuery still mounted? If not - it won't display anything.

Upvotes: 1

Related Questions