Photo by Ashwini Chaudhary(Monty) on Unsplash
To make an HTTP request using GraphQL in React, you can use the Apollo Client library. Here are the basic steps:
1. Install the required packages:
npm install apollo-boost react-apollo graphql
2. Import the required packages:
import React from 'react';
import { ApolloProvider } from 'react-apollo'; import ApolloClient from 'apollo-boost'; import gql from 'graphql-tag'; import { Query } from 'react-apollo';
3. Create a new instance of ApolloClient with the server URL:
const client = new ApolloClient({ uri: 'http://localhost:4000/graphql' });
4. Create a GraphQL query using gql:
const GET_USERS = gql` { users { id name email } } `;
5. Wrap your root component with the `ApolloProvider` and pass the client:
``const App = () => (
<ApolloProvider client={client}>
<div>
<h2>GraphQL Example</h2>
<Query query={GET_USERS}>
{({ loading, error, data }) => {
if (loading) return <p>Loading…</p>;
if (error) return <p>Error :(</p>;
return data.users.map(({ id, name, email }) => (
{name} {email} )); }} );
export default App;``
6. The Query component takes the GET_USERS query as a prop and renders the data returned from the server. If there’s an error or the data is still loading, it will show a message accordingly.
GraphQL uses the HTTP protocol to make requests to the server. The HTTP request contains a JSON-encoded body with the GraphQL query or mutation.
Here’s the result of the GraphQL HTTP request made:
``POST /graphql HTTP/1.1
Host: localhost:4000
Content-Type: application/json
Accept: application/json
{
"query": "query ($id: ID!) { user(id: $id) { id name email } }",
"variables": { "id": "1" }
}``
In this example, we’re sending a POST request to the /graphql endpoint on localhost:4000. The request body is a JSON object with two properties:
- query: the GraphQL query to execute, which in this case is a user query that takes an id variable.
- variables: an object containing the values of any variables used in the query. In this case, we’re passing in an id variable with a value of “1”.
The server responds with a JSON-encoded body that contains the results of the query:
``HTTP/1.1 200 OK
Content-Type: application/json
{
"data": {
"user": {
"id": "1",
"name": "John Doe",
"email": "john.doe@example.com"
}
}
}``
In this example, the server returns the id, name, and email fields for the user with an id of ”1". The response is also a JSON object with a data property that contains the results of the query.