I'm trying this. But with String!
gets the error, Errors: Variable "$slug" of required type "String!" was not provided.
Errors: Variable "$slug" of required type "String!" was not provided.
even query(the below works well on localhost:8000/___graphql). Then I tried String
without string. Then the error is gone, but I always get the same content which is markdown's info.
Does anyone have any ideas to solve this issue?
my repo: https://github.com/koji/portfolio
Thank you in advance,
error
import { useStaticQuery, graphql } from "gatsby";
export const getPostData = () => {
const data = useStaticQuery(
graphql`
query getPostData($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
frontmatter {
title
date
}
html
}
}
`);
return data.markdownRemark;
};
returns the same content
import { useStaticQuery, graphql } from "gatsby";
export const getPostData = () => {
const data = useStaticQuery(
graphql`
query getPostData($slug: String) {
markdownRemark(fields: { slug: { eq: $slug } }) {
frontmatter {
title
date
}
html
}
}
`);
return data.markdownRemark;
};
trying to get the title of a markdown file
import * as React from "react";
import Layout from "../components/layout";
import { getPostData } from "../components/hooks/getPost";
const Blog = () => {
const data = getPostData();
console.log(data);
return (
<Layout>
<h1>{data.frontmatter.title}</h1>
<p>{data.frontmatter.date}</p>
{data.html}
</Layout>
);
};
export default Blog;
gatsby-node.js
const path = require("path");
// onCreateNode API
module.exports.onCreateNode = ({node, actions}) => {
const { createNodeField } = actions;
// console.log(node);
if(node.internal.type === 'MarkdownRemark') {
const slug = path.basename(node.fileAbsolutePath, '.md');
createNodeField({
node,
name: 'slug',
value: slug
});
}
}
module.exports.createPages = async({ graphql, actions}) => {
const { createPage } = actions;
const blogTemplate = path.resolve('./src/templates/blog.tsx');
const res = await graphql(`
query {
allMarkdownRemark {
edges {
node {
fields {
slug
}
}
}
}
}
`);
res.data.allMarkdownRemark.edges.forEach(({node}) => {
createPage({
component: blogTemplate,
path: `/blog/${node.fields.slug}`,
context: {
slug: node.fields.slug,
}
});
})
}
You'll have to use a regular page query in your post template, ie export const query = graphql...
The reason is that useStaticQuery
& <StaticQuery>
just won't receive the context
you've passed into createPage
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.