Ways to fetch GraphQL on Frontend

Accessing data from a GraphQL API in the frontend will always involve making a POST call.There are several ways to fetch data from a GraphQL API on the frontend, including using:

Axios

Let's imagine we have a GraphQL query, and in order to retrieve the order data, we need to supply the id of the order as an argument to the query.

query orderById($id: Int!) {
  order_by_pk(id: $id) {
    id
    customer {
      email
    }
    order_date
    product
  }
}

The graphql language consists of two components called "query" and "variables." In order to create a request body, you will need to make a POST call using axios.

Lets initialize a axios instance and pass the request body to the instance as shown below

let graphQLInstance = axios.create({
  baseURL: "https://youapp.sample.com",
  headers: {
    "Content-Type": "application/json"
  }
})

let result = await graphQLInstance.post("/graphql", {
  query:"query orderById($id: Int!) { order_by_pk(id: $id) { id customer { id } order_date product }}",
  variables: {
    id: 1
  }
});

Apollo Client

Apollo Client is a powerful JavaScript library for building client applications that communicate with a GraphQL server. It provides a simple and intuitive API for managing GraphQL data in the client, and offers features such as caching, pagination, and real-time updates.

To use Apollo Client, you first need to configure a client instance with the necessary connection details as shown below

npm install @apollo/client graphql

Initialize

Initialize the ApolloClient instance to the root of App component

import {
  ApolloClient,
  InMemoryCache,
  ApolloProvider,
  gql,
} from '@apollo/client'

const client = new ApolloClient({
  uri: 'https://tesla.com/v1/graphql',
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${process.env.token}`,
  },
  cache: new InMemoryCache(),
})

export default function App() {
  return (
    <div className="App">
      <ApolloProvider client={client}>
        <User />
      </ApolloProvider>
    </div>
  )
}

Fetch the data using useQuery hook in component

import { useQuery, gql } from '@apollo/client'

const GET_ORDERS = gql`
  query orderById($id: Int!) {
    order_by_pk(id: $id) {
      id
      customer {
        email
      }
      order_date
      product
    }
  }
`

const Order = ({ userid }) => {
  const { loading, error, data } = useQuery(GET_ORDERS, {
    variables: { id: userid },
  })
  console.log('data', data)
  if (loading) return null
  if (error) return `Error! ${error}`
  return data && <pre>{JSON.stringify(data, null, 2)}</pre>
}

const User = () => {
  let [userid, setuserid] = React.useState('')
  <div>
    <p>Search User</p>
    <input
      type="text"
      value={userid}
      placeholder="Search"
      onChange={e => setuserid(e.target.value)}
    ></input>

    {userid && <Order userid={userid} />}

    <button onClick={handleSearch}>Search</button>
  </div>
}

In the above code the order component executes GET_ORDERS query with useQuery hook

const Order = ({ userid }) => {
  const { loading, error, data } = useQuery(GET_ORDERS, {
    variables: { id: userid },
  })
  console.log('data', data)
  if (loading) return null
  if (error) return `Error! ${error}`
  return data && <pre>{JSON.stringify(data, null, 2)}</pre>
}

Selvaganesh © 2023.