0
0
GraphqlDebug / FixBeginner · 4 min read

How to Handle Error State in Apollo Client Effectively

To handle error state in Apollo Client, use the error property returned by the useQuery or useMutation hooks. Check if error exists and display a message or take action accordingly to inform users or retry the operation.
🔍

Why This Happens

When you run a query or mutation with Apollo Client, errors can happen due to network issues, server problems, or bad requests. If you don't check for errors, your app might crash or show wrong data without explanation.

javascript
import { useQuery, gql } from '@apollo/client';

const GET_USER = gql`
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      name
    }
  }
`;

function UserProfile({ id }) {
  const { data, loading, error } = useQuery(GET_USER, { variables: { id } });

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return <p>User name: {data.user.name}</p>;
}
Output
Error: Cannot read property 'name' of undefined (if query fails or user not found)
🔧

The Fix

Add error handling by checking the error property from Apollo's hook. Show a friendly message or fallback UI when an error occurs to improve user experience.

javascript
import { useQuery, gql } from '@apollo/client';

const GET_USER = gql`
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      name
    }
  }
`;

function UserProfile({ id }) {
  const { data, loading, error } = useQuery(GET_USER, { variables: { id } });

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return <p>User name: {data.user.name}</p>;
}
Output
<p>User name: Alice</p> (when query succeeds) or <p>Error: Network error: Failed to fetch</p> (when query fails)
🛡️

Prevention

Always check for error in Apollo hooks to avoid crashes. Use try/catch blocks for mutations with async/await. Consider showing retry buttons or fallback UI. Use Apollo DevTools and logging to catch errors early.

⚠️

Related Errors

Common related errors include:

  • Network errors: caused by connectivity issues.
  • GraphQL errors: returned by the server for invalid queries.
  • Cache errors: when Apollo cache is out of sync.

Handling these involves checking error.networkError and error.graphQLErrors separately for detailed messages.

Key Takeaways

Always check the error property from Apollo hooks to handle failures gracefully.
Display user-friendly messages or fallback UI when errors occur to improve experience.
Use try/catch with mutations to catch errors in async operations.
Leverage Apollo DevTools and logging to detect and debug errors early.
Inspect networkError and graphQLErrors for detailed error info.