TanStackT
TanStack11mo ago
1 reply
colourful-plum

Why data value of queries is not updated on queryClient.setQueryData(['grid'], updatedGrid)

The data variable returned to React component is not updated on setQueryData causing the isDirty function to pretend data is always dirty even after saving data server side.

Query code :
export const useUpdateGrid = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (grid: IGrid) => updateGrid(grid), // Fonction qui envoie la requête
    onSuccess: updatedGrid => {
      queryClient.setQueryData(['grid', updatedGrid._id], updatedGrid);
      queryClient.invalidateQueries({ queryKey: ['grids'] });
    },
  });
}


Component code:
const { isFetching, data: serverGrid } = useFetchGrid(id);

//Always true since serverGrid is not updated after setQueryData
const isDirty = useMemo(() => {
  return JSON.stringify(currentGrid) !== JSON.stringify(serverGrid);
}, [currentGrid, serverGrid]);

  const handleSaveGridAction = async (): Promise<void> => {
    if (!currentGrid) return;

    updateGridMutation.mutate(currentGrid, {
      onSuccess: (grid: IGrid) => {
        setCurrentGrid(grid);
      },
    });
  };


What is the issue there ?

How to implement isDirty so ?
Screenshot_2025-03-07_at_12.44.39.png
Was this page helpful?