Blog>
Snippets

Error Handling in Asynchronous Operations

Provide examples on handling and displaying errors to the user when API calls fail, using the error state provided by React Query's useQuery and useMutation hooks.
import { useQuery } from 'react-query';
import axios from 'axios';

const fetchUserData = async () => {
  return await axios.get('/user');
};

const UserComponent = () => {
  const { data, error, isError } = useQuery('userData', fetchUserData);

  if (isError) {
    // Displaying error message to the user
    return <div>Error: {error.message}</div>;
  }

  // Render user data if no error
  return <div>{data?.data.name}</div>;
};
This code snippet demonstrates how to use React Query's useQuery hook for fetching user data from an API and handling errors. If an error occurs during the data fetch operation, the error is displayed to the user.
import { useMutation } from 'react-query';
import axios from 'axios';

const createUser = async (user) => {
  return await axios.post('/users', user);
};

function CreateUserComponent() {
  const { mutate, isError, error } = useMutation(createUser, {
      onError: (error) => {
        // Handle error state here, e.g., logging or displaying a notification
        console.error('Error creating user:', error);
      }
  });

  const handleSubmit = (user) => {
    mutate(user);
  };

  return (
    <div>
      {isError && <p>Error: {error.message}</p>} // Displaying error message to the user on failed mutation
      <button onClick={() => handleSubmit({ name: 'New User' })}>Create User</button>
    </div>
  );
}
Here, we're using React Query's useMutation hook to perform a POST request for creating a new user. The onError callback handles any errors, logging them to the console. Additionally, an error message is displayed to the user directly in the UI if there is a problem during the mutation.