You might not need a library to query GraphQL in Remix
View in Sanity Studio2023-09-18
For production applications, you may prefer to use a library to query GraphQL. That library likely has advanced features like caching.
However, if you need data quickly, you don't even need a library to perform a GraphQL query or may benefit from a light one.
GraphQL requests can be performed using the Fetch API. Your query will need to be stringified to JSON and sent as a "post" request.
In this example Remix route, a public GraphQL API for country info is targeted to return details about the country GB
.
import { useLoaderData } from "@remix-run/react";
const QUERY_URL = "https://countries.trevorblades.com/graphql";const QUERY = { query: `{ country(code: "GB") { name emoji } }`,};
export async function loader() { const { data } = await fetch(QUERY_URL, { method: "post", headers: { "Content-Type": "application/json" }, body: JSON.stringify(QUERY), }).then((res) => res.json());
return { country: data.country };}
export default function Fetch() { const { country } = useLoaderData();
return <div>{JSON.stringify(country)}</div>;}
This is an unwieldy way to write GraphQL queries, however, so a small library can go a long way.
graphql-request is a deliberately lightweight library for querying GraphQL data. It contains a few helpers that make querying GraphQL easier without the overhead of application-wide providers or caching settings.
npm i graphql-request
Here's the same loader again, but with gql
to apply syntax highlighting to the query and a static type for the returned data.
import { request, gql } from "graphql-request";import { useLoaderData } from "@remix-run/react";
const QUERY_URL = "https://countries.trevorblades.com/graphql";const QUERY = gql` { country(code: "AU") { name emoji } }`;
type Data = { country: { name: string; emoji: string; };};
export async function loader() { const data = await request<Data>(QUERY_URL, QUERY);
return { country: data.country };}
export default function Fetch() { const { country } = useLoaderData();
return <div>{JSON.stringify(country)}</div>;}
(The motivation for this blog post was that the top result on Google for "graphql remix" was an over-complicated, out-of-date guide. I hope this helps you if you stumbled upon the same thing!)