...

/

Apollo Client Error Handling in React

Apollo Client Error Handling in React

In this lesson, you will learn how to handle GraphQL errors and network errors when using Apollo Client in React.

Before diving into GraphQL mutations in React with Apollo Client, this lesson should clarify error handling with Apollo in React.

The error handling happens on two levels:

  • the application level
  • query/mutation level

Both can be implemented with the two cases that follow. On a query level, in your Profile component, you have access to the query data and loading properties. Apart from these, you can also access the error object, which can be used to show a conditional error message.

Press + to interact
...
import RepositoryList from '../Repository';
import Loading from '../Loading';
import ErrorMessage from '../Error';
...
const Profile = () => (
<Query query={GET_REPOSITORIES_OF_CURRENT_USER}>
{({ data, loading, error }) => {
if (error) {
return <ErrorMessage error={error} />;
}
const { viewer } = data;
if (loading || !viewer) {
return <Loading />;
}
return <RepositoryList repositories={viewer.repositories} />;
}}
</Query>
);
export default Profile;

Whereas the ErrorMessage component from the src/Error/index.js could look like the following:

Press + to interact
import React from 'react';
import './style.css';
const ErrorMessage = ({ error }) => (
<div className="ErrorMessage">
<small>{error.toString()}</small>
</div>
);
export default ErrorMessage;

If we now try to change the name of a ...