rbi-learning / Today-I-Learned

1 stars 0 forks source link

09/02 Apollo Client #175

Open fhern077 opened 4 years ago

fhern077 commented 4 years ago

Apollo Client

Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL.Use it to fetch, cache, and modify application data, all while automatically updating your UI.

We don't need apollo client in order to make a graphql call we made our own graphql call using

const getCityByName = (cityName) => `
query {
  getCityByName(name: "${cityName}", country: "US", config: { units: imperial }){
    id
    name
    country
    weather{
      summary{
        title
        icon
      }
      temperature{
        actual
    feelsLike
        min
        max
      }
      wind{
        speed
        deg
      }
      clouds{
        humidity
      }
    }
  }
}`;

export { getCityByName };

The issue here is we don't have all the flexibility and functionality available to us given by apollo client (queries, mutations, subscriptions, pagination, fragments etc.). Out of the box we get caching in order to not need to make duplicate requests.

In order to recreate our previous hand-rolled graphql function we can leverage apollo's gql string

import { gql } from "@apollo/client";

export const CITY_WEATHER = gql`
  query CityWeather($name: String!) {
    getCityByName(name: $name, country: "US", config: { units: imperial }) {
      id
      name
      country
      weather {
        summary {
          title
          icon
        }
        temperature {
          actual
          feelsLike
          min
          max
        }
        wind {
          speed
          deg
        }
        clouds {
          humidity
        }
      }
    }
  }

useLazyQuery will allow us to limit the amount of times we send queries only based on certain non refreshing actions

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

function DelayedQuery() {
  const [dog, setDog] = useState(null);
  const [getDog, { loading, data }] = useLazyQuery(GET_DOG_PHOTO);

  if (loading) return <p>Loading ...</p>;

  if (data && data.dog) {
    setDog(data.dog);
  }

  return (
    <div>
      {dog && <img src={dog.displayImage} />}
      <button onClick={() => getDog({ variables: { breed: 'bulldog' } })}>
        Click me!
      </button>
    </div>
  );
}