To use GraphQL with React.js, we need to use some libraries that allow client-server communication. One such popular library is Apollo Client. Here is a step-by-step guide to setting up GraphQL in a React.js application using Apollo Client.
1. Install Apollo Client and relevant dependencies:
You can install the required dependencies using the following command.
```
npm install @apollo/client graphql
```
1. Connect Apollo Client to the GraphQL Endpoint:
You connect Apollo Client to the GraphQL endpoint in the main JavaScript file that you would include into your HTML file.
```
import { ApolloClient, InMemoryCache } from ‘@apollo/client’;
export const client = new ApolloClient({
uri: ‘https://your-graphql-endpoint’, //your GraphQL server url
cache: new InMemoryCache()
});
```
1. Provide the Apollo Client instance via context:
Wrap your app with ApolloProvider, which is imported from `@apollo/client`.
```
import React from ‘react’;
import ReactDOM from ‘react-dom’;
import { ApolloProvider } from ‘@apollo/client’;
import App from ‘./App’;
import { client } from ‘./client’; //file where you have created client
ReactDOM.render(
);
```
1. Use GraphQL data in your React components:
Fetching a GraphQL query and displaying the result in a React component requires use of the `useQuery` hook from `@apollo/client`.
Here’s an example where we fetch a list of todos:
```
import React from ‘react’;
import { gql, useQuery } from ‘@apollo/client’;
const GET_TODOS = gql`
query GetTodos {
todos {
id
type
}
}
`;
function TodoList() { const { loading, error, data } = useQuery(GET_TODOS);
if (loading) return ‘Loading…’; if (error) return `Error! ${error.message}`; return (This hooks fetches the GraphQL query `GET_TODOS`, and renders the `TodoList` React component. The `useQuery` hooks also automatically sets up a component state for loading and error handling.
1. Mutations in Apollo
Much like we use useQuery to fetch data from our GraphQL server, we make changes with mutations.
Here’s the outline code of an addTodo component:
```
import React from ‘react’;
import { gql, useMutation } from ‘@apollo/client’;
const ADD_TODO = gql`
mutation AddTodo($type: String!) {
addTodo(type: $type) {
id
type
}
}
`;
function AddTodo() { let input; const [addTodo, { data }] = useMutation(ADD_TODO);
return (export default AddTodo;
```
This is just a simple setup, Apollo Client with React is very robust and can be customized for more complex applications.