gatsby-plugin-graphql-loader v1.0.2
gatsby-plugin-graphql-loader
Uses graphql-tag/loader to allow .graphql and .gql files to be imported into components for client-side GraphQL queries.
Use Cases
Supported:
gatsby-plugin-graphql-loader can load queries stored in .gql / .graphql files used for client-side GraphQL queries to external APIs.
Not supported:
.gql / .graphql queries loaded with gatsby-plugin-graphql-loader cannot be used for queries to Gatsby's internal GraphQL engine.
Installing
The graphql-tag package needs to be installed alongside this plugin. To install both:
With NPM
npm i gatsby-plugin-graphql-loader graphql-tagWith Yarn
yarn add gatsby-plugin-graphql-loader graphql-tagUsage
Add "gatsby-plugin-graphql-loader" to the plugins array in gatsby-config.js:
// gatsby-config.js
module.exports = {
plugins: ["gatsby-plugin-graphql-loader"];
}Now you can import .graphql and .gql in your component files.
Example
For a full working example, see github.com/NWRichmond/gatsby-plugin-graphql-loader-demo.
Suppose you have src/queries/get-comments-by-first-name.gql which contains the following query:
# getCommentsByFirstName.gql
query 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:
// UserInfo.js
import React from "react";
import { useQuery } from "@apollo/client";
import GET_USER_COMMENTS from "../queries/getCommentsByFirstName.gql";
const UserInfo = ({ firstname }) => {
const { data, loading, error } = useQuery(GET_USER_COMMENTS, {
variables: { firstname },
});
if (error) {
return <p>Error Querying Data</p>;
}
if (loading) {
return <p>Loading...</p>;
}
const [user] = data.users;
return (
<>
<h3>First Name</h3>
<p>{user.firstname}</p>
<h3>Comments</h3>
<ul>
{user.comments.map(({ id, text }) => (
<li key={id}>{text}</li>
))}
</ul>
</>
);
};
export default UserInfo;