Gatsby, StaticQuery, and PageQuery — Day 3

Image by Design_Miss_C on Pixabay

Today is my 3rd day with Gatsby, if you read my previous post about GraphQL, I had a pending task bind the data from GraphQL using StaticQuery component and query in Pages.

StaticQuery is used to connect our components with GraphQL, it can wrap all component and bring access to the query result.

Page Query is const with the GraphQl query and passing throw the page to bring access to the query data and can be used only in Pages.

Using StaticQuery

I will create a functional component named teams.js, and import StaticQuery and GrapQL from the Gatsby.

We change the component to return the component <StaticQuery> with 2 props query to write or set the GraphQL query and render get data as an argument, and return our div with display data and show the data like always in React.

In the previous posts, I wrote a query for getting teams list from siteMetada, we can copy the query and set it into const.

import React from "react";
import { StaticQuery, graphql } from "gatsby";

const queryNBATeams = graphql`
{
nba: site {
siteMetadata {
nbateams {
name
}
}
}
}
`
;
export default function Nba() {
return (
<StaticQuery
query=
{queryNBATeams}
render={data => {
const teams = data.nba.siteMetadata.nbateams;
return (
<div>
<h1>NBA Teams</h1>
<ul>
{teams.map((item, index) => (
<li key={index}>{item.name}</li>
))}
</ul>
</div>
);
}}
/>
);
}

Query in Page

Create a new page called files.js, it is a functional component and import Layout from ‘components/layout’ and GraphQL from Gatsby.

import Layout from "../components/layout";
import { graphql } from "gatsby";

Export a const with the query with .js files filter created in my previous post.

export const query = graphql`
{
allFile(filter: { extension: { eq: "js" } }) {
edges {
node {
relativePath
name
}
}
}
}
`
;

The final step sends the data to the component like props and to access the data less verbose, use a destruct to set the edges values.

import React from "react";
import Layout from "../components/layout";
import { graphql } from "gatsby";

export default function files({ data }) {
const files = data.allFile.edges;
return (
<Layout>
<div>
<h2>All JS</h2>
<ul>
{files.map(item => {
return <li>{item.node.name}</li>;
})}
</ul>
</div>
</Layout>
);
}

export const query = graphql`
{
allFile(filter: { extension: { eq: "js" } }) {
edges {
node {
relativePath
name
}
}
}
}
`
;

There you have it! Page query and StaticQuery are a little bit similar but with a different approach, Now you are ready to query data and bind your pages and components.

I hope you enjoyed and be a little bit useful.