Feb 8, 2024

Apollo Client Network Interceptors in React Native

Unlock the full potential of Apollo Client in Expo. Explore network interceptors for seamless GraphQL interactions in your React Native applications in our latest article.
Amritansh Kumar Mishra
Amritansh Kumar MishraSoftware Engineer - III
Jajala Trived Kumar
Jajala Trived KumarSenior Software Engineer - I
lines

Introduction

This guide will unravel the wonders of Apollo Client's interceptor and demonstrate how effortlessly it can be integrated into your Expo project. Whether you are a seasoned developer or just embarked on your React Native journey with Expo, get ready to add a touch of magic to your GraphQL interactions.

What is Apollo Client Interceptor, Anyway?

Apollo Client's network interceptor is like having a personal assistant for your network requests. It allows you to intervene at various stages of the data-fetching process, enabling you to customize, log, authenticate, or gracefully handle errors. This is about making requests and crafting an experience tailored to your application's unique needs.

Basic Setup of Apollo Client in an Expo Project

1. Setup

Create a new expo project by running the following command:

We are using the gluestack framework here to create an expo project. You can choose to create a normal expo app by running:

2. Install Dependencies

Applications that use Apollo Client require two top-level dependencies:

  • @apollo/client: This single package contains virtually everything you need to set up Apollo Client. It includes the in-memory cache, local state management, error handling, and a React-based view layer.
  • graphql: This package provides logic for parsing GraphQL queries.

Run the following command to install both of these packages:

3. Initialize Apollo Client

Next, we will initialize ApolloClient, passing its constructor a configuration object with the uri and cache fields:

4. Add Provider

Add provider by running the following command:

5. Usage of Apollo Network Interceptor

Implement Authentication, error handling, and debouncing globally.

I. Authentication

Run the following command:

II. Error-handling

Apollo Client stands ready to assist you in gracefully handling errors that may arise during GraphQL operations, ensuring a seamless user experience. It provides tools to effectively address different error types, empowering you to display informative messages and take appropriate actions when issues occur.

Types Of Errors

Executing GraphQL operations on a remote server can result in two types of error:

  • GraphQL Errors
  • Network Errors

If the query produces one or more errors, this object contains either an array of graphQLErrors or a single networkError. Otherwise, this value is undefined.

GraphQL Errors

GraphQL errors are returned directly from the GraphQL server. These errors could manifest for a multitude of reasons, including validation failures, authentication issues, or permission problems.

  • Syntax errors (e.g., a query was malformed)
  • Validation errors (e.g., a query included a schema field that doesn't exist)
  • Resolver errors (e.g., an error occurred while attempting to populate a query field)

To provide insights into GraphQL-specific issues, Apollo Client meticulously gathers any GraphQL errors and presents them within the error.graphQLErrors array within your operation hooks. This detailed information empowers you to pinpoint and resolve problems originating from the GraphQL server itself. Notably, Apollo Server signals complete operation failures with 4xx status codes, while partial data responses accompanied by resolver errors are indicated with a 200 status code. This distinction allows you to tailor your error-handling strategies accordingly.

Example error response

Network Errors

To stay informed about network hiccups, Apollo Client diligently captures any network errors and surfaces them within the error.networkError field of your operation hooks, such as useQuery. This allows you to quickly identify and address communication issues with your GraphQL server.

Error Policies:

none: If the response includes GraphQL errors, they are returned on error.graphQLErrors and the response data is set to undefined even if the server returns data in its response. This means network errors and GraphQL errors result in a similar response shape. This is the default error policy.

ignore: graphQLErrors are ignored (error.graphQLErrors is not populated), and any returned data is cached and rendered as if no errors occurred.

all: Both data and error.graphQLErrors are populated, enabling you to render both partial results and error information.

That’s enough theory. Let us get to it with an example:

III. Debouncing

Adding debounce in the Apollo Client network layer brings several benefits, especially when dealing with scenarios where frequent or rapid requests can lead to inefficiencies or unnecessary load on the server. Here are some theoretical points explaining the advantages of incorporating debounce in the Apollo Client network layer:

  • Optimized Server Resources
  • Improved User Experience
  • Avoidance of Unnecessary Rendering
  • Enhanced Stability in Unstable Network Conditions

We have implemented debounce globally using the *apollo-link-debounce* library. You can check more information here.

Summing Up

Apollo Client's network interceptor in React Native provides a flexible way to intercept and modify network requests and responses. Whether you need to log requests, add authentication headers, or modify payload such as we have implemented debounce part, or handle errors, network interceptors offer a powerful mechanism to customize your GraphQL client behavior. By leveraging these interceptors effectively, you can enhance the reliability, security, and maintainability of your React Native applications that use Apollo Client for GraphQL operations. You streamline development and maintenance by applying these global strategies across your Apollo Client network layer. Consistent authentication, error handling, and debouncing practices eliminate the need for redundant code, making your codebase cleaner, more maintainable, and less prone to bugs.

Book a Discovery Call.

blog logo