Blog>
Snippets

Graceful Error Feedback with React Query

Demonstrate how to utilize React Query's `error` object within queries to render user-friendly error messages, improving the user experience in the event of query failures.
import { useQuery } from 'react-query';
import React from 'react';
Imports useQuery hook from react-query library and React.
const fetchUserData = async () => {
  const response = await fetch('/api/user/data');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};
Defines an asynchronous function to fetch user data from an API endpoint. Throws an error if the response is not okay.
const UserProfile = () => {
  const { data, error, isError } = useQuery('userData', fetchUserData);

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

  return (
    <div>
      <h1>User Profile</h1>
      {/* Render user data */}
    </div>
  );
};
Defines a React component that uses the useQuery hook to fetch and display user data. If an error occurs, displays a user-friendly error message.
export default UserProfile;
Exports the UserProfile component for use in other parts of the application.