usequery apollo client hook code example

Example 1: useLazyQuery

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>
  );
}

Example 2: apoolo uselaxyQuery bypass cache

const { data: cachedData } = useQuery(MyQuery, { fetchPolicy: 'cache-only', variables });
const [executeMyQuery, { data: queryData, loading, error }] = useLazyQuery(MyQuery, {
  fetchPolicy: 'network-only'
});
const data = queryData || cachedData;

Tags:

Misc Example