Skip to content

Instantly share code, notes, and snippets.

@andflett
Created July 1, 2024 12:13
Show Gist options
  • Save andflett/693fee04fa6cfa93038f3041881de065 to your computer and use it in GitHub Desktop.
Save andflett/693fee04fa6cfa93038f3041881de065 to your computer and use it in GitHub Desktop.

GraphQL

We use GraphQL Code Generator with the client preset to make it simple to write queries, mutations, and fragments in a way which is typesafe and extensible. This article is a good place to start if you're new to GraphQL and React, or are more familiar with the old way of using plugins to generate separate React hooks for each query.

To encourage consistancy in what and how we display our oft complex data models, we provide a handful of global queries. However, if you do need a query or mutation that is only going to be used in a single component, it's advisable to use graphql inline with useQuery, rather than cluttering up the global generated queries. See usage below.

For the global scope - to ensure we're not loading more data than is nessesary - we build up our queries as such:

  1. order.common.graphql - put data in here that we want to show everywhere for an order, or when it is used as a nested connection (e.g. prescriptions.orders)
  2. order.summary.graphql - for use in list views for the most part
  3. order.graphql - the full, nested data model, mostly used when showing the entire order on it's own page

Usage

Global

Global queries, mutations, and fragments are stored in /graphql/queries and are generated automatically when you run npm run graphql. They are then available to import from @graphql to use in your components. For example:

import { GetAccountDocument } from "graphql/generated/graphql";

//...

const { data, loading, error, refetch } = useQuery(GetAccountDocument, {
  variables: { id: accountId },
});

Colocated

Any queries using graphql() from graphql/generated/gql can be colocated with the component that uses them, alternatively, if you want to colocate but break out from the component itself, then you can instead build your query in a separate file within the same directory, e.g.:

/app/[accountId]/[patientId]/toolbar/history/index.tsx
/app/[accountId]/[patientId]/toolbar/history/index.graphql.ts # Colocated GraphQL queries required for the index
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment