Skip to main content

GraphQL

A country browser on top of the public Countries GraphQL API. It uses the same requests and hooks as a REST app; only the adapter changes.

beginnergraphqluseFetchcachetypescript
import { useFetch } from "@hyper-fetch/react";
import type { GraphQLFormattedError } from "graphql";
import { useState } from "react";

import { getCountries, getCountry } from "./api";

const continents = [
{ code: "EU", name: "Europe" },
{ code: "AS", name: "Asia" },
{ code: "AF", name: "Africa" },
{ code: "NA", name: "North America" },
{ code: "SA", name: "South America" },
{ code: "OC", name: "Oceania" },
];

// GraphQL errors are a list. Network and timeout errors use the same shape.
const formatErrors = (errors: GraphQLFormattedError[]) => errors.map((error) => error.message).join(", ");

const CountryDetails = ({ code }: { code: string }) => {
const { data, error, loading } = useFetch(getCountry.setPayload({ code }));

if (loading && !data) return <article aria-busy="true">Loading country...</article>;
if (error) return <article className="error">Could not load the country: {formatErrors(error)}</article>;
if (!data?.country) return <article>Country not found.</article>;

const { country } = data;

return (
<article>
<header>
<h3>
{country.emoji} {country.name}
</h3>
<small className="muted">{country.native}</small>
</header>
<dl>
<dt>Capital</dt>
<dd>{country.capital ?? "-"}</dd>
<dt>Currency</dt>
<dd>{country.currency ?? "-"}</dd>
<dt>Languages</dt>
<dd>{country.languages.map((language) => language.name).join(", ") || "-"}</dd>
</dl>
</article>
);
};

export const App = () => {
const [continent, setContinent] = useState("EU");
const [selected, setSelected] = useState<string | null>(null);

// `setPayload` sets the GraphQL variables. Each continent gets its own cache entry.
const { data, error, loading } = useFetch(getCountries.setPayload({ continent }));

return (
<main className="container">
<hgroup>
<h1>Countries</h1>
<p>A GraphQL API with typed queries and variables. Visited continents and countries load from the cache.</p>
</hgroup>
<nav className="tabs">
{continents.map((item) => (
<button
key={item.code}
type="button"
className={item.code === continent ? undefined : "outline secondary"}
onClick={() => setContinent(item.code)}
>
{item.name}
</button>
))}
</nav>
<div className="grid-2">
<section>
{loading && !data && <p aria-busy="true">Loading countries...</p>}
{error && <p className="error">Could not load countries: {formatErrors(error)}</p>}
<ul className="list">
{data?.countries.map((country) => (
<li key={country.code}>
<button
type="button"
className={country.code === selected ? undefined : "outline secondary"}
onClick={() => setSelected(country.code)}
>
{country.emoji} {country.name}
</button>
</li>
))}
</ul>
</section>
{selected ? <CountryDetails code={selected} /> : <p className="muted">No country selected.</p>}
</div>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/graphql hyper-fetch-react-graphql && cd hyper-fetch-react-graphql && npm install && npm run dev
What it shows
  1. GraphqlAdapter turns every request of the client into a GraphQL operation.
  2. Typed queries set the response and the variables with the usual createRequest generics.
  3. Variables in the payload are set with setPayload() and become a part of the cache key.
  4. GraphQL errors arrive as the typed error list, like any other failed response.

How it works​

  1. api.ts creates the client with the endpoint URL and calls setAdapter(GraphqlAdapter()). The error generic of createClient is set to GraphQLFormattedError[], because the adapter reports failures as a list.

  2. The GraphQL document goes in endpoint. A plain string works, and so does a gql document from graphql-tag. The payload generic types the variables:

    const getCountry = client.createRequest<{ response: { country: Country | null }; payload: { code: string } }>()({
    endpoint: `query Country($code: ID!) { country(code: $code) { name capital } }`,
    });
  3. App calls useFetch(getCountries.setPayload({ continent })). The adapter builds the cache key from the operation name and the variables, so Countries for Europe and for Asia are two cache entries, and switching back is instant.

  4. CountryDetails runs a second query with getCountry.setPayload({ code }) for the selected country.

  5. Queries are sent with POST by default. useFetch still sends them through the fetch dispatcher and caches them like GET requests.

When to use it
  • Apps that talk to a GraphQL API and want HyperFetch caching, queues and hooks.
  • Projects that mix REST and GraphQL: each client has its own adapter, and the hooks stay the same.

Summary

setAdapter(GraphqlAdapter()) is the only GraphQL-specific line. Documents go in endpoint, variables in the payload, and the cache keeps one entry per set of variables.