Apollo Client GraphQL with Reactjs

Apollo Client GraphQL with Reactjs

11 January 2022

Integrating GraphQL APIs in reactjs was a little tricky with GraphQL rely upon, Now Apollo Client made GraphQL Integration and Usage very easy even though we can call the GraphQL API a Restful call.

But managing the data needs to Integrate third-party libraries like Redux or MobX. Now with Apollo Client, it handles API calling along with State Management.

Now we will go through the Integration part in Reactjs.

  • Step 1

    Create a project locally with a create react app.
    Lets Install the dependency package for apollo client

    npm install @apollo/client graphql
    

    apollo/client: package help to setup the apollo client in the project and has InMemoryCache, state management, error handling.
    Graphql: Helps to parse the GraphQL queries.

  • Step 2

    Now we will start configuring the Apollo Client.
    In index.js file import the following modules
    ApolloClient, InMemoryCache, ApolloProvider

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

    Client was initialized ApolloClient its constructor with a configuration object with uri and cache fields

    const client = new ApolloClient({ uri: 'Base-url', cache: new InMemoryCache() });
    

    Uri specifies the GraphQL server.
    Cache is an instance of memory. It uses cache query results after fetching the data.

    Now client was ready with configuration. Now we need to Hook up or wrap our React app with Apollo Provider. Which provides access to GraphQL data throughout the react APP.

    Lets see the sample code of index.js:

    import React from 'react';
     import { render } from 'react-dom';
     import { ApolloClient, InMemoryCache, ApolloProvider, useQuery, gql } from "@apollo/client"; const client = new ApolloClient({ uri: 'https://48p1r2roz4.sse.codesandbox.io', cache: new InMemoryCache() }); 
    function App() { 
    return ( 
       
    My first Apollo app
    ); } render( , document.getElementById('root'), );

    Now total setup of the Apollo client was done. Now we will look into calling the GraphQL API.
    To call the fetch API we need to useQuery React Hook which helps in calling the query and shares GraphQL data with UI.

    Gql is the template literal in which the query we want to execute should be wrapped.
    Lets see sample fetch Query:

    const EXCHANGE_RATES = gql` 
       query GetExchangeRates { rates(currency: "USD") { currency rate } } 
    `;
    

    useQuery hook returns us loading, error status with help of this props we can show loading screen and show alerts for users when API was failed.
    And we get responses in data prop.

    useQuery also provides us with a refetch prop which helps to call the query whenever it is needed.

search
Request a quote