Integrating GraphQL in React.js: Simplifying Data Fetching
Tags: react, javascript, webdev, graphql
Published: 2023-11-09 18:45:50

GraphQL has revolutionized the way developers interact with APIs. Unlike REST APIs, GraphQL allows clients to request exactly the data they need, no more, no less. In React.js, integrating GraphQL enhances the component's data-fetching capabilities by making the data retrieval process more efficient and precise. In this blog, we'll walk through the steps to integrate a GraphQL API with a React.js application using Apollo Client.

**What is GraphQL?**
GraphQL is a query language for your API, and a server-side runtime for executing those queries by parsing your data. It isn't tied to any specific database or storage engine and is instead backed by your existing code and data.

To integrate GraphQL into a React.js application, we will use `Apollo Client`, a popular, feature-rich GraphQL client that provides a comprehensive approach to data management in modern web applications.

**Setting Up Apollo Client**
To integrate Apollo Client into your React app, you'll first need to install it:

```
npm install @apollo/client graphql
```
Next, you’ll need to set up `ApolloClient `and the `ApolloProvider`. This provider component uses React's Context API to make a client instance available throughout the component tree.

For demonstration purposes, we'll use the `SpaceX GraphQL API`, which is a public API that provides data about SpaceX launches.

Here's how you configure Apollo Client with this real GraphQL endpoint:

![Appolo Client with React](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bh9nmh3tb2tkftkt3lkm.png)

With this configuration, your React application is now ready to query the SpaceX API and render the data in your UI. You can use the provided `useQuery`, `useMutation`, and `useSubscription `hooks to interact with the API according to your application's needs.

**Fetching Data in the Dashboard Component**
Within the Dashboard component, you can now make use of Apollo Client's `useQuery `hook to fetch data from the SpaceX API. The `useQuery `hook leverages React's Hooks API to fetch and load data from GraphQL queries.

Here's an example of how to use `useQuery` to retrieve a list of SpaceX launches: 

![Fetching data with graphql API in React](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4r4eijjehej2vwagfony.png)

In this code, we are creating a simple UI that maps over the array of past launches returned by the `GET_LAUNCHES `query. Each launch is displayed in its own div with details such as mission name, launch date. 

**Advanced Data Fetching Techniques with Apollo Client**
As you become more comfortable with the basics of fetching data using Apollo Client, you'll soon run into scenarios that require more advanced techniques. Let's delve into some of these techniques to enhance your React applications.

Using variables in your GraphQL queries allows you to write dynamic and reusable queries that can adapt based on user interaction or component state changes. Let's walk through an example where users can filter a list of launches by a mission name that they input into a search field.

First, we define our GraphQL query to accept a variable for the `mission name`:

```
// Define the GraphQL query with a variable
const GET_LAUNCHES_BY_MISSION_NAME = gql`
  query GetLaunchesByMissionName($missionName: String!) {
    launchesPast(find: { mission_name: $missionName }) {
      mission_name
      launch_date_local
    }
  }
`;
```
Next, we'll create a React component with a search field where users can type in a `mission name`. We'll use Apollo Client's `useQuery `hook to fetch the launches based on the `mission name `provided.

Here's a concise example of how that might look in your React component:

![User Search example with GraphQL](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jgt4p3r6b4yss3nlekrc.png)

In the `LaunchesSearch `component, we are maintaining the state for `missionName `which is updated whenever the input field changes. The `useQuery `hook then uses this state as a variable for the GraphQL query, which will refetch the data whenever the `missionName `changes. The skip option is used to avoid executing the query before the user has entered a search term.

This pattern is highly effective for creating interactive and responsive interfaces that provide feedback to the user as they search or filter data.

The complete working code example you can found here.
[https://codesandbox.io/s/react-js-with-graphql-forked-tcmz2v?file=/src/App.js](https://codesandbox.io/s/react-js-with-graphql-forked-tcmz2v?file=/src/App.js)

**Conclusion**

We've seen how to integrate a `GraphQL` API into a React.js application using `Apollo Client`, from setting up Apollo Client and configuring it to use a real GraphQL endpoint, to fetching data and displaying it with a styled component. GraphQL’s power lies in its ability to allow clients to request exactly what they need, and Apollo Client makes it easy to fetch, cache, and manage that data in a React.js application.

Remember, the `SpaceX API` used in this example is a real public API, which makes it an excellent resource for practicing GraphQL queries and mutations.

Integrating GraphQL with React.js can significantly improve the performance and user experience of your application by avoiding over-fetching or under-fetching of data. With tools like Apollo Client, it becomes relatively straightforward to manage your data and keep your UI in sync with the state of your data in the backend.

I hope this guide has been helpful to get you started with GraphQL in React.js applications. With the basic setup done, you're now ready to explore more advanced features of Apollo Client such as local state management, error handling, and subscriptions for real-time updates.

Keep coding, and may your queries always return exactly what you expect!