Blog>
Snippets

Query Invalidation after Data Mutation

Illustrate how to invalidate and refetch queries to ensure the UI reflects updated data after a mutation operation.
const mutation = useMutation(updateTodo, {
  onSuccess: () => {
    queryClient.invalidateQueries('todos')
  }
});
In this code snippet, we're using the `useMutation` hook from React Query to perform a mutation operation, such as updating a todo item. The `updateTodo` function represents the mutation function that carries out the update operation. Upon a successful mutation (`onSuccess`), we invalidate the 'todos' query using `queryClient.invalidateQueries('todos')`. This invalidation prompts React Query to refetch the 'todos' data, ensuring the UI reflects the updated state of the data.
async function updateData(newData) {
  await mutation.mutateAsync(newData);
}
This function `updateData` is defined to execute our mutation operation. It calls `mutateAsync` on our `mutation` object, passing the `newData` to be updated. The `mutateAsync` method returns a promise, allowing us to use `await` to pause execution until the mutation is complete, triggering the invalidation and refetching as defined in our mutation's `onSuccess`.
queryClient.invalidateQueries('todos', { exact: true });
Here, we're explicitly invalidating the 'todos' query cache by calling `queryClient.invalidateQueries`. The `exact: true` option means that only the queries with the exact match of the query key will be invalidated. This is useful for cases where you might have multiple queries related to 'todos' but only want to refetch the data for this specific query.