Blog>
Snippets

Configuring Query Invalidation for Fresh Data

Explain how to configure query invalidation and refetching strategies after data mutations to ensure the UI reflects the most current server state.
import { useMutation, useQueryClient } from 'react-query';

const updateData = async (newData) => {
  // assume this function updates data on the server
  // and returns the updated data
  return fetch('/update-data', {
    method: 'POST',
    body: JSON.stringify(newData),
    headers: {
      'Content-Type': 'application/json'
    },
  }).then(res => res.json());
};

function MyComponent() {
  const queryClient = useQueryClient();

  const { mutate } = useMutation(updateData, {
    onSuccess: () => {
      // Invalidate and refetch
      queryClient.invalidateQueries('dataQueryKey');
    },
  });

  const updateHandler = (newData) => {
    mutate(newData);
  };

  return (
    // UI elements here
  );
}
This code demonstrates how to use useMutation hook from React Query to update data on the server and invalidate a specific query by its key ('dataQueryKey') to refetch fresh data. onSuccess callback of useMutation is used to invalidate the query after the mutation succeeds.