How to Debug Apollo Client in React
Debugging Apollo Client in React is essential for tracking down network issues, cache inconsistencies, and query failures. This article provides a straightforward guide on how to inspect your Apollo cache, log queries and mutations, handle errors globally, and utilize the official developer tools to streamline your debugging process.
1. Use the Apollo Client DevTools
The most effective way to debug Apollo Client is by using the official Apollo Client DevTools extension, available for Chrome and Firefox.
Once installed, it integrates directly into your browser’s developer tools and provides three key features: * GraphiQL: An in-browser IDE that allows you to test queries and mutations against your schema using your application’s current network configuration. * Cache Inspector: A visual explorer that lets you view the entire state of your in-memory cache, inspect specific cache keys, and see how data is normalized. * Watched Queries: A live list of all active queries currently being watched by your React components, showing their variables, loading states, and fetch policies.
To enable the DevTools in production or non-development environments,
set the connectToDevTools option to true when
initializing your client:
const client = new ApolloClient({
uri: 'https://your-api.com/graphql',
cache: new InMemoryCache(),
connectToDevTools: true,
});2. Debug with Apollo Link Logger
If you prefer debugging directly inside your browser’s console, you
can use Apollo Link to log every outgoing request and incoming response.
The easiest way to achieve this is by installing
apollo-link-logger.
npm install apollo-link-loggerYou can then add it to your Apollo Client link chain:
import { ApolloClient, InMemoryCache, HttpLink, from } from '@apollo/client';
import loggerLink from 'apollo-link-logger';
const httpLink = new HttpLink({ uri: 'https://your-api.com/graphql' });
const client = new ApolloClient({
link: from([loggerLink, httpLink]),
cache: new InMemoryCache(),
});This will log detailed, readable information to your console, including query names, variables, execution times, and returned data or errors.
3. Implement Global Error Link
To catch and debug GraphQL errors or network issues globally before
they reach your React components, use the
@apollo/client/link/error package. This allows you to log
errors to your external monitoring tools or standard console.
import { onError } from '@apollo/client/link/error';
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.forEach(({ message, locations, path }) =>
console.error(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
)
);
}
if (networkError) {
console.error(`[Network error]: ${networkError}`);
}
});Combine this errorLink with your main
HttpLink using the from utility to ensure all
operations pass through your error handler.
4. Inspect Local State and Component Props
When debugging specific React components, make use of the
destructured states provided by the useQuery and
useMutation hooks. Always check the error and
loading states rather than assuming data is present.
const { loading, error, data } = useQuery(GET_USERS);
if (loading) return <p>Loading...</p>;
if (error) {
// Inspect the raw error object
console.log(JSON.stringify(error, null, 2));
return <p>Error loading users.</p>;
}By combining the visual insights of the Apollo Client DevTools with programmatic console logging and global error handling, you can quickly isolate whether a bug resides in your React components, the local Apollo cache, or your backend GraphQL API.