Query GraphQL in Remix in less than 60 seconds

Created on November 12, 2023 at 11:37 am

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 ORG query or may benefit from a light one.

Copy link to this section Without a library

GraphQL requests can be performed using the Fetch API PRODUCT . 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 PERSON .

Copy import { useLoaderData } from "@remix-run/react" ; const QUERY_URL = "https://countries.trevorblades.com/graphql" ; const QUERY = { query : ` { country(code: " GB PERSON ") { name emoji } } ` , } ; export async function loader ( ) { const { data } = await fetch ( QUERY_URL , { method : "post" , headers : { " Content-Type WORK_OF_ART " : "application/json" } , body : JSON . stringify PERSON ( QUERY ) , } ) . then ( ( res ) => res . json ( ) ) ; return { country : data . country } ; } export default function Fetch PERSON ( ) { const { country } = useLoaderData ( ) ; return < div > { JSON . stringify PERSON ( country ) } </ div > ; }

This is an unwieldy way to write GraphQL queries, however, so a small library can go a long way.

Copy link to this section With a simple library

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.

Copy PERSON 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.

Copy import { request , gql } PERSON from "graphql-request" ; import { useLoaderData } from "@remix-run/react" ; const QUERY_URL = "https://countries.trevorblades.com/graphql" ; const QUERY = gql ` { country ( code : " AU WORK_OF_ART " ) { name emoji } } ` ; type Data ORG = { 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 PERSON ( ) { const { country } = useLoaderData ( ) ; return < div > { JSON . stringify PERSON ( country ) } </ div > ; }

(The motivation for this blog post was that the top result on Google ORG for "graphql remix" was an over-complicated, out-of-date guide. I hope this helps you if you stumbled upon the same thing!)

Connecting to blog.lzomedia.com... Connected... Page load complete