Skip to main content

Graphql best practices

Graphql queries/mutations used across different files in the same folder

For queries/mutations used across different files in the same folder (e.g. a USERS query that is used in src/profile/user-page.tsx and in src/profile/user-popup.tsx), place then into a separate file within that folder and import them into the components that need them. For example:

In a file called queries.ts in src/profile/data/queries.ts:

export const USERS = gql`
query {
users {
id
name
}
}
`;

In the component:

import { USERS } from "./data/queries";

const { data, loading, error } = useQuery<UserReturnType>(USERS);

Graphql queries/mutations used across different files in different folders

For queries/mutations used across different files in different folders (e.g. a USERS query that is used in src/profile/user-page.tsx and in src/postings/my-page.tsx), place then into _shared and import them into the components that need them. If you do this, make sure that both places have the exact same query. For example:

In a file called queries.ts in src/shared/data/queries.ts:

export const USERS = gql`
query {
users {
id
name
}
}
`;

In the component:

import { USERS } from "../../shared/data/queries";

Always define and export graphql return types where the query lives

For example, if you have a query like this:

export const USERS = gql`
query {
users {
id
name
}
}
`;

Then you should also define and export a return type like this:

export interface UserReturnType {
id: string;
name: string;
}

And then use it in the component like this:

const { data, loading, error } = useQuery<{ users: UserReturnType }>(USERS);

Make sure that the type you define is based on the query that you wrote, and matches the schema on the backend, including the optional properties.