gatsby-plugin-graphql-loader
A Gatsby plugin for loading .graphql
and .gql
files with the help of graphql-tag/loader.
This is for:
Loading queries for browser runtime GraphQL operations, such as with Apollo Client.
This is not for:
Loading queries used at build time.
For more information on the distinction between runtime vs. build time, see the Gatsby docs.
Installing
The graphql-tag package needs to be installed alongside this plugin. To install both:
Using Yarn
yarn add gatsby-plugin-graphql-loader graphql-tag
Using NPM
npm i gatsby-plugin-graphql-loader graphql-tag
Usage
Add the plugin to gatsby-config.js
:
// In your gatsby-config.jsplugins: `gatsby-plugin-graphql-loader`;
Now you can import .graphql
and .gql
files directly into your components.
Example
A working example is show in this GitHub repository.
Suppose you have src/queries/get-comments-by-first-name.gql
which contains the following query:
# get-comments-by-first-name.gqlquery getUserComments($firstname: String!) { users(where: { firstname_eq: $firstname }) { firstname comments { text } }}
In a component file (say, /src/components/user-info.js
), import the query from the .gql
file, make the query with Apollo Client, and render out the information returned by the query:
// user-info.js;;; const UserInfo = { const data loading error = ; const user = !loading && !error ? datausers : null; if error return <p>Error Querying Data</p>; return error || !loading && <> <h3>First Name</h3> <p>userfirstname</p> <h3>Comments</h3>" " <ul> usercomments </ul> </> ;}; ;