Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject certain context into all pages in Gatsby?

Tags:

gatsby

Using gatsby-node.js and createPages I can query something using graphql and create pages using that something as page context. So those pages can use that something as parameter in their queries.

The problem I'm facing is that I don't want to use createPages. I'm completely fine with pages that are created by default (from gatsby-plugin-page-creator), I just want all of them to have something from graphql as a context.

Basically I want a global context (which I get from gatsby graphql) to be available for all pages.

There is onCreatePage hook but unfortunately graphql is not available there according to https://github.com/gatsbyjs/gatsby/issues/3121#issuecomment-348781341.

like image 260
MnZrK Avatar asked Nov 16 '18 08:11

MnZrK


People also ask

How do you make a dynamic page in The Great Gatsby?

Gatsby's File System Route API lets you dynamically create new pages from data layer nodes by naming your files with a special syntax. File System Routes only work on files in the src/pages directory (or subdirectories). To create a new collection route, you name your file {nodeType. field}.

What are SRC pages in Gatsby?

/src This directory will contain all of the code related to what you will see on the frontend of your site (what you see in the browser), like your site header, or a page template. “src” is a convention for “source code”.

What is GraphiQL tool?

What is GraphiQL? GraphiQL is the GraphQL integrated development environment (IDE). It's a powerful (and all-around awesome) tool you'll use often while building Gatsby websites. You can access it when your site's development server is running—normally at http://localhost:8000/___graphql .


1 Answers

What about this... you can try using the onCreateNode() hook instead inside your gatsby-nodejs file. E.g.:

const allMyPageNodes = [];

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions;
  if(...) { //whatever filtering you need to select JUST pages in your site
    const mySpecialContext = "blah"; //whatever your global context settings are
    createNodeField({ node, name: "myglobal", value: mySpecialContext });
    allMyPageNodes.push(node);
  }
}

```

Then in all graphql queries thereafter, for pages, the graphql payload should have edge.node.fields.myglobal populated and you should be able to do whatever you like with it. Also have a look at https://www.gatsbyjs.org/docs/static-query/ for querying directly from inside a component.

HTH.

like image 116
yen Avatar answered Oct 20 '22 17:10

yen