Blog>
Snippets

Error Handling with TanStack Query

Show how to handle errors in data fetching or mutations using TanStack Query, including displaying error messages to the user.
import { useQuery } from 'react-query';

function FetchData() {
  const { data, error, isError } = useQuery('data', fetchDataFunction);

  if (isError) return <div>An error occurred: {error.message}</div>;

  return <div>{JSON.stringify(data)}</div>;
}
This code demonstrates how to use useQuery from TanStack Query for data fetching. It includes error handling by checking if isError is true and displaying the error message to the user.
import { useMutation } from 'react-query';

function UpdateData() {
  const { mutate, error, isError } = useMutation(updateDataFunction, {
    onError: (error) => {
      alert(`An error occurred: ${error.message}`);
    }
  });

  return <button onClick={() => mutate(dataToUpdate)}>Update Data</button>;
}
This code snippet demonstrates how to use useMutation from TanStack Query for sending data updates to the server. It includes error handling through an onError callback, where an alert is displayed to the user in case of an error.