Using the page's query params as params in the page level query

Viewed 559

In gatsbyJS there is a way to specify page level queries but from whatever i've read only way to pass params to the gatsby query is when creating the page (via page context).

For example, below $slug is passed to the page when creating it. Is there another way to pass $slug (maybe via a query param value).

export const query = graphql`
  query($slug: String) {
    mdx(frontmatter: {slug: { eq: $slug }}) {
      frontmatter {
        title
        author
      }
      body
    }
  }
`;
1 Answers

I open this new page /search?slug=test and when search loads i read query param slug and use that to query within the graphql query (and load the page)

The short answer is that you can't since you are on the same page (/search), which is created and populated using a Gatsby page query in the build-time, so there's no way that you can change that "static" query with a dynamic content coming from a URL parameter.

What you can do, however, is to use plain JavaScript to get the URL parameter and use a dynamic filter to change the result of the page query and display it as you wish in the /search page.

Related