React Query and SWR
Gqlts does not replace your React data library. Use the generated client or operation helpers inside SWR and TanStack Query fetchers.
SWR
Install SWR with your package manager of choice:
npm install swr
pnpm add swr
yarn add swr
bun add swrDeclare the fetcher outside the hook call so TypeScript can infer the generated client result.
import useSWR from 'swr';
import { createClient } from './generated';
const client = createClient({ url: '/api/graphql' });
function fetchCountries(continent: string) {
return client.query({
countries: [
{ filter: { continent: { eq: continent } } },
{
name: true,
code: true,
},
],
});
}
export function CountriesPanel({ continent }: { continent: string }) {
const { data, error, isLoading } = useSWR(['countries', continent], ([, value]) => fetchCountries(value));
if (isLoading) return <p>Loading</p>;
if (error) return <p>Failed to load countries</p>;
return <pre>{JSON.stringify(data?.data?.countries, null, 2)}</pre>;
}TanStack Query
npm install @tanstack/react-query
pnpm add @tanstack/react-query
yarn add @tanstack/react-query
bun add @tanstack/react-queryimport { useQuery } from '@tanstack/react-query';
import { createClient } from './generated';
const client = createClient({ url: '/api/graphql' });
export function CountriesPanel({ continent }: { continent: string }) {
const countries = useQuery({
queryKey: ['countries', continent],
queryFn: () =>
client.query({
countries: [
{ filter: { continent: { eq: continent } } },
{
name: true,
code: true,
},
],
}),
});
return <pre>{JSON.stringify(countries.data?.data?.countries, null, 2)}</pre>;
}Operation helpers
When the data library or framework owns transport, use generateQueryOp and send { query, variables } yourself.
import { generateQueryOp } from './generated';
const operation = generateQueryOp({
countries: {
name: true,
code: true,
},
});