Skip to main content

Command Palette

Search for a command to run...

useQuery and useLazyQuery-Apollo Client(React)

Published
β€’4 min read
useQuery and useLazyQuery-Apollo Client(React)
P

Being in love with coding, I'm looking for opportunities to utilize and grow my technical abilities as a programmer (full stack developer, frontend or backend )

Introduction to GraphQl:

As we heard most of the time about SQL -Structured Query Language so what is GrapghQL 😁. GraphQL is a query Langauge which is a declerative way of fetching data and makes a query smarter, faster and developer-friendly, designed by Facebook. As we have been designing the endpoint and queries for quite a long and the only problem with that is over-fetching and under-fetching. sometimes the data is less so we have to make another query and sometimes the data are very large that we don't use all of the data, we just use selective points of the data. Nothing big much of worry but when your business is at a scale of Facebook, millions or billions of people will be querying data every single second then it can be a little bit expensive on the cost of the server as a lot of queries will be fetched and data is been transferred.

Difference between REST API and GraphQl

For example, If we want to fetch certain information on our website such as name, age, height and a high score of the top 5 players that have played in the T20 cricket World Cup 2020 and now assume the data will be fetchingπŸ₯Έ . It will be surely over-fetching, we will be fetching a lot of information and then we will be nitpicking the information that is been asked and most of our REST API looks like this /player/player/:id/country and often these endpoints don't have any ids will give you all of the information for that endpoints and which has ids will give you one particular resource and whether all of that information you required or not, however, it will be served to you. you will not only get the name, and address but get all the other information like height, gender and so many now imagine you are fetching 100 ids and you will making 100 API requests and 100 responses will be given to you and you only collecting 4,5 information which is very very costly.

So, thanks to GraphQL where you can make selective endpoints which means you can go a little bit deeper into your API endpoints and can select information on it. It will give you exactly the information that you asked for. nothing more and nothing less. it always returns predictable results.

useQuery Hook

The user query React hook is the recommended/ primary method to fetch the data. when you are using the useQuerry hook you can track the data from loading state to success. and in case you have any error while fetching the data it also provides the error state so which is a complete package to track all the states while making a request.

This article assumes that you've already set up Apollo Client and have wrapped your React app in an ApolloProvider Component

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

const GET_CARS = gql`
  query allCars($id:String!) {
    cars (id:$id){
      id
      name
      model
    }
  }
`;


function CarsQuery({id}) {
    const { loading, error, data } = useQuery(GET_CARS,{
    variables:{id}
     });

    if (loading) {
        return <span>Loading...</span>;
    }

    if (error) {
        return <span>Something went wrong: ${error}</span>;
    }

    if (data) {
        return (
            <div>
                <h1>Cars</h1>
                <h1>{data.cars.name} </h1>
            </div>
        );
    }

    return null;
}

export default CarsQuery;

useLazyQuery

The useLazyQuery React hook also works as same the useQuery Hook, However, the main difference is that along with the three different states {loading, error, data) it provides the query function that you call whenever you're ready to execute the query and Importantly, It does not immediately execute the associated query. This hook is perfect when you want to fetch the data in response to the different events ("click"). In addition to this, you can modify the variables or pass the different variables when you are fetching the query in response to events.

import React from 'react';
import { useLazyQuery } from '@apollo/client';

function CarsLazyQuery({id}) {
  const [getCars, { loading, error, data }] = useLazyQuery(GET_CARS);

  if (loading) return <p>Loading ...</p>;
  if (error) return `Error! ${error}`;

  return (
    <div>
      {data?.cars && <h1>{data.cars.name} </h1>}
      <button onClick={() => getCars({ variables: { id: '1' } })}>
        ClickOne
      </button>
      <button onClick={() => getCars({ variables: { id: '2' } })}>
        ClickTwo
      </button>
    </div>
  );

Note πŸ“–: Whenever we fetch the data using the useQuery/useLazyQuery hook it will automatically cache those results locally which makes later executions of that same query extremely fast.

Thank you for reading this article, Happy coding !! πŸ’»β€οΈ