Blog>
Snippets

Selective Invalidation After Updating a Resource

Demonstrate how to selectively invalidate and refetch data for a specific resource after it's been updated, using query keys to target the exact invalidated queries.
import { useMutation, useQueryClient } from 'react-query';

const updateResource = async (resourceData) => {
  // API call to update the resource on the server
  return fetch('/api/resource/' + resourceData.id, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(resourceData),
  }).then(res => res.json());
};
Defines an asynchronous function updateResource that makes a PUT request to update a resource on the server. This function is intended to be used with a mutation.
const useUpdateResource = () => {
  const queryClient = useQueryClient();
  return useMutation(updateResource, {
    onSuccess: () => {
      // Invalidate and refetch queries with the queryKey 'resources'
      queryClient.invalidateQueries(['resources']);
    },
  });
};
Defines a custom hook useUpdateResource that uses the useMutation hook from react-query. It performs the updateResource mutation and, on success, invalidates queries having the queryKey 'resources', causing them to refetch and update the UI accordingly.
// Using the custom hook in a component to update a resource
function UpdateResourceButton({ resourceData }) {
  const { mutate } = useUpdateResource();

  return (
    <button onClick={() => mutate(resourceData)}>
      Update Resource
    </button>
  );
}
Implements a React component that uses the useUpdateResource custom hook. It renders a button that, when clicked, triggers the mutation to update the resource and consequently refreshes related queries.