Search code examples
graphinternationalizationgatsbycontentfulgatsby-plugin

Gatsby useStaticQuery with locale


I'm using gatsby with contentful data source and gatsby-plugin-react-int.

On each page of my site present the block with latest news, so I use the useStaticQuery hook to get data for the "News" component

export const useStaticNewsQuery = () => useStaticQuery(graphql`
query StaticNews {
  allContentfulNews {
    nodes {
      node_locale
      gatsbyPath(filePath: "/news/{contentfulNews.slug}")
      slug
      title
      body {
        body
      }
      publishDate
    }
  }
}
`)

But as my site is multilingual - I need to get localized news related to the current locale.

As I know - staticQuery does not allow passing variables.

But how can I request in the component only news related to the current locale?

If I'll use pageQuery - I will have to make the same request for each page that includes "News" component in my application and pass the result through the props/context to my "News" component

Maybe I should make some magic in the gatsby-node.js as querying data related to the current locale and pass it through some global context? Also - the same stuff will be with header, footer and other parts of page, that will be rendered by separated components and placed on almost all pages, but should be depended on the current locale


Solution

  • Given your scenario and your requirements I can only imagine:

    1. Create one staticQuery (useStaticQuery) for each locale to get the news: then you will only need to get the current locale and trigger the needed query like:
      let news;
      if (currentLocale = 'en') news = useStaticNewsQueryEn();
      els if (currentLocale = 'es') news = useStaticNewsQueryEs();
      
    2. As you pointed, use a filtered page query with the value of the current locale of the page
    3. Tweak your gatsby-node.js to get the data there and share it to the needed component (should be always a template or a dynamically created page) and share it via context.

    Regarding your shared components (footer, header, etc) you can always render the needed component based on the locale (conditional rendering), that shouldn't be a problem.

    You should see what's better performant and more scalable/flexible in your specific use-case.