DEV Community

Cover image for Apollo Client GraphQL with React
aravind_akay
aravind_akay

Posted on

Apollo Client GraphQL with React

In this article we gonna discuss about the basics about graphQL and how to use it in your react app.

What is GraphQL ?

GraphQL is a Query Language invented by facebook. It solves many of the shortcomings and inefficiencies while interacting with REST API.

It’s more flexible than REST APIs because it allows frontend clients to request exactly the data format the client needs. REST APIs on the other hand typically send back a fixed data format that often contains redundant data that is not required by the client, as example frontend client wants only user email, why I should call web API for a user and get all user information, and we will get an email, full name, age, etc… We only need an email attribute of the user.

In layman's term it is a query language acts as a filter between the data that is fetching and the data we actually get.(or) it is a syntax that describes how to ask for the data.

Why GraphQL ?

You can extract the information you want

Traditionally you make the request to the server and you make use of the data you need but it can actually contain other properties that you may not need to the particular use case.

With GraphQL, users can query the data they are looking for. not less, not more.

Data Fetching

Lets say you have an users api and you want to fetch specific users's post and friends. For this scenario you want to make the endpoints like

/users/:id/posts
/users/:id/friends

or you would get all the info from users/:id and you would use it.

With GraphQL, you can specify with the one route (users/:id) and you can change your query according to your requirement.

Image description

Image description

The first query will extract the posts and the later query will extract the friends

You can also specify the fields you want in your friends object as well

Image description

Use Apollo Client with React

Apollo Client allows you to fetch data from your GraphQL server and use it in complex and reactive UIs.

You need to install apollo client and graphql package to get started.

npm install @apollo/client graphql --save
Enter fullscreen mode Exit fullscreen mode

Now it needs to configure the endpoint of your GraphQL API.

index.js
import React from 'react';
import ReactDOM from 'react-dom';

import App from './App';
import {ApolloClient, InMemoryCache, ApolloProvider} from '@apollo/client'

const client = new ApolloClient({
  uri : "https://rickandmortyapi.com/graphql/",
  cache: new InMemoryCache()
})


ReactDOM.render(  
  <ApolloProvider client={client}>
  <App />
  </ApolloProvider>
,document.getElementById('root'));

Enter fullscreen mode Exit fullscreen mode

I am using rickandmorty api for this implementation.I've come across another api crwnclothing and you can use this as well.

With the ApolloClient you have to provide uri. InMemoryCache is something acts like an actual cache thats gonna memoize the query we hit and everytime you hit the query it will search for the query in here.

You have to wrap your application with ApolloProvider at the top heirarchy of your app. So I did it in index.js

Our First Query

Typically a query would look like an object that defines the fields we want. You can name the query if you want. The following screenshots would show how to query it in GraphiQL and their results. You can visit to rickandmortyapi and try out the queries.

Image description

As I said you can extract the exact information you want.

Image description

You need to import gql and useQuery from apollo/client

import {gql, useQuery} from '@apollo/client'
Enter fullscreen mode Exit fullscreen mode

Define our Query

Image description

CharactersList.js
import React from 'react'
import {gql, useQuery} from '@apollo/client'

const GET_CHARACTERS = gql`
    query fetchAllCharacters {
    characters {
        results {   
         id
         name
        image
        }
    }
}
`

function CharactersList() {
    const {data, loading, error} = useQuery(GET_CHARACTERS);
    if(loading) {
        return <div> Loading...</div>
    }

    if(error){
        return <div>Error occured {error.message}</div>
    }  
    return (
    <div className='characters-list'>{data.characters.results.map((character) => {
        return <div>
            <img src={character.image} />
            <p>{character.name}</p>
        </div>
    })}</div>
  )
}

export default CharactersList
Enter fullscreen mode Exit fullscreen mode

The output of this characters list would be like

Image description

useQuery is purely for GET request only. There is an another hook for useMutation which is for POST and PUT request.

If you want a single Character, you have to pass the Query with variables. The query would look like


const GET_CHARACTER_BY_ID = gql`
    query fetchCharacterById($id:ID!) {
        character(id : $id) {
            id
            name
            image

        }
    }
`

Enter fullscreen mode Exit fullscreen mode

Here We have to specify what kind of parameter that we gonna pass. This specific ID data type gonna assign to the variable id in the character query.

Now you have to wonder , how am gonna pass the id into this thing. Its very simple.

 const {data,loading,error} = useQuery(GET_CHARACTER_BY_ID, {variables : {id: 4}})
Enter fullscreen mode Exit fullscreen mode

Here I pass 4 as the harcoded value but in real scenario it would be a variable.

I hope this would be the best primer to get started with apollo client.Kudos. Happy Coding!

Top comments (0)