In Gatsby I'm trying to use dynamic query in my wrapPageElement, but apparently it doesn't run at all. I use the same syntax as in normal page queries:
export const query = graphql `
query PageLayout($locale: String) {
pages: allMarkdownRemark(sort: {fields: [frontmatter___title], order: DESC}, filter: {frontmatter: {draft: {nin: true}}, fields: {locale: {eq: $locale}, collection: {in: ["pages"]}}}) {
nodes {
frontmatter {
title
}
fields {
slug
}
}
}
}`;
Any proposal how to implement? The idea is that, there is a Nav element, which is part of the main Layout, so it should be able to list my pages.
Thanks for all
I'm trying to use dynamic query in my
wrapPageElement
.
That will never work. wrapPageElement
is a shared API between gatsby-browser.js
and gatsby-ssr.js
that wraps component across pages, it's not intended to trigger queries, it doesn't make sense because page queries happens in pages (or templates) and that context is missing in the wrapPageElement
.
The idea is that, there is a Nav element, which is part of the main Layout, so it should be able to list my pages.
You can use a useStaticQuery
to display all pages like you are doing in the query above, but you don't need to filter it at all. Static queries don't accept dynamic values, like $locale
is (hence the name) so any kind of filtering would need to be applied in JavaScript code directly.
It's quite common to use isolated components, something like:
import { useStaticQuery, graphql } from "gatsby";
export const useNavQuery = () => {
const { pages } = useStaticQuery(
graphql`
query PageLayout {
pages: allMarkdownRemark(
sort: { fields: [frontmatter___title], order: DESC }
filter: {
frontmatter: { draft: { nin: true } }
collection: { in: ["pages"] }
}
) {
nodes {
frontmatter {
title
}
fields {
slug
}
}
}
}
`
);
return pages;
};
Then:
import React from "react"
import { useNavQuery } from "../hooks/use-site-nav"
export default function Nav() {
const pages = useNavQuery ()
return <h1>/* your loop through pages */</h1>
}