How to Set Up GraphQL in a React App

HOW TO SET UP GRAPHQL IN A REACT APP?

2 min Aug 23, 2021 Manish Kumar MOBILE Views : 2051
GraphQL is a query language that allows you to get exactly what you are looking for from several resources in a single request. It is designed to make clients like web apps more performant and easier to work with backend data. This article will show you how to use Apollo Client to incorporate GraphQL into your React app. To retrieve data from graphQL and REST endpoints, first, configure Apollo Client and then useQuery. This article requires that you have a basic understanding of React Hooks.

To begin, create a new React project and install @apollo/client, a reliable and mature graphQL library, into the new React project. Apollo assists your app with state management and in-memory caching. In comparison to a React Redux project, this allows you to accomplish more with less code.

Apolloclient Installation Process

To use ApolloClient in your React native app to query a graphQL API, you must first create a client and make it available to relevant components.

There are two bits of configuration that must be completed:

●    You can control how data flows from your graphQL queries and changes to your backend and in-app state management using the link. Adding custom headers and routing to REST and graphQL endpoints are examples of this.

●    When you already have the data, the cache allows you to avoid making unnecessary network requests.

Making Apolloclient Available To The Rest Of Your Application

You may use React's Context API with the client configuration to allow your child components to access your configuration and make queries and mutations. You have imported your previous client and wrapped everything in the ApolloProvider component. These modifications are required so that the ExchangeRatesPage component you will construct in the next section knows how to retrieve data.

Creating a Graphql Query Using a Component

With the ApolloClient in place, child App.js components can query data using the useQuery and useLazyQuery hooks. The useQuery hook is explained in this section. Make a file called src/ExchangeRatePage.js. When this component is loaded, the query to the server is immediately made, and the loading attribute is set to true. Your component is rerendered and the data property is populated as soon as the data is returned. 

You May Also Like to Read: What is GraphQL

Note that there is a lot less setup required to get started with querying data. The properties for loading and error states are taken care of for you. You can use the useLazyQuery hook and call the return method to trigger the fetch process if you want additional control overloading. You can use the useLazyQuery hook and call the return method to trigger the fetch process if you want additional control overloading.

Graphql can be Used to Query Rest Resources.

You can still use Apollo and GraphQL to query data if you have a set of REST endpoints. You will need to install apollo-rest-link to perform this. To install the required packages, input the following commands: 

yarn add graphql-anywhere apollo-link-rest

Then, in src/ApolloClient/client, make the necessary changes: 

import { ApolloClient, ApolloLink, InMemoryCache } from "@apollo/client";

import { RestLink } from "apollo-link-rest";

import { HttpLink } from "apollo-link-http";

const restLink = new RestLink({
endpoints: {
   openExchangeRate: "https://open.exchangerate-api.com/v6/",
 },
});

const httpLink = new HttpLink({
uri: "https://48p1r2roz4.sse.codesandbox.io",
});

export const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.from([restLink, httpLink]),
});


You have set up two ApolloLinks now:

●    Requests to your graphQL endpoint are handled by HttpLink.
●    Requests to one or more REST endpoints are handled by RestLink.

The @rest graphQL directive can be used to activate your RestLink. Your EXCHANGE RATES query should be updated. With your graphQL endpoint, Apollo Client will send a request to your REST endpoint. The path supplied in the @rest directive and the endpoint configured in client.js will be combined to create the URI for your rest endpoint. 

The graphQL endpoint's rates are combined with the REST endpoint's openExchangeRate field at the root. From the standpoint of the client, this is advantageous since you can take advantage of Apollo's caching and state management without having to totally rewrite your backend in GraphQL.

Understanding Graphql and It’s Installation Process 

GraphQL is a query language that intends to replace REST APIs by providing a clear description of the data in the API to users. You can rapidly connect your React.js application to an API by combining these two technologies. For connecting to a GraphQL API, there are numerous packages available. 

Apollo is one of the most widely used, but you can also use Axios or the built-in JavaScript fetch function. You will use Axios for this application, but you should also look into Apollo or any other GraphQL/React packages that are available. You may use React's Context API with the client configuration to allow your child components to access your configuration and make queries and mutations. 

You need to have Node v6 installed before you begin, though the examples should work in prior versions of Node as well. We won't be using any language features that require transpilation in this article, but we will utilize ES6 features like Promises, classes, and fat arrow functions, so you should familiarise yourself with them beforehand. 

You will need a schema to describe the Query type, as well as an API root with a function called a "resolver" for each API endpoint to handle GraphQL queries. You may write this code in a file called server for an API that simply returns "Hello world!" js. 

Also Read: The Future of Xamarin: .NET MAUI

The GraphQL response should be printed out. You'll probably want to perform GraphQL queries through an API server rather than using a command-line tool for real applications. 

Bottom Line

Modern web apps development require a lot of interaction with outside data. Querying data from REST and GraphQL endpoints becomes considerably easier with Apollo and GraphQL. You might wish to look into other Apollo features like mutations and subscriptions as a future step.