bkoodaa
bkoodaa

Reputation: 5322

Gatsby: how to pass data to React Context at build time

I have a Gatsby site where I'm using React Context to provide a theme (heading, footer, styling, etc.) Now I want to add last build time to the footer, e.g. "Last updated: 13 Nov 23:08". How can I do this?

Obviously, if I just put the buildTime inside the Context Provider or anywhere within the React Component that creates it, then the time will update with every refresh (as opposed to every build).

I figured I should be able to set buildTime = new Date() in gatsby-node.js createPages API, and then pass the buildTime in pageContext. But after passing it down a couple React components I end up needing to pass it to <ThemeContext.Consumer>. I can't pass props to the Context Consumer.

The best solution I've come up with is writing build time to a file and then loading that information from a file, which is obviously horrible, so it would be nice if there was a better solution.

Upvotes: 3

Views: 1041

Answers (1)

mindlis
mindlis

Reputation: 1677

You can use GraphQL to fetch build time in the Component which needs it (rather than passing it down through context provider). The StaticQuery below is executed at build time only.

import React from 'react'
import { useStaticQuery, graphql } from 'gatsby'

const IndexPage = () => {
  const data = useStaticQuery(query)

  return (
    <>
      <p>This site was last built on:</p>
      <p>{data.site.buildTime}</p>
    </>
  )
}

export default IndexPage

const query = graphql`
  query Info {
    site {
      buildTime(formatString: "DD/MM/YYYY")
    }
  }
`

From https://www.lekoarts.de/en/blog/tips-and-tricks-for-gatsby#date-of-last-build

Upvotes: 6

Related Questions