I am getting data in Gatsby by Apollo dynamically from WP. New post appears in archive posts but a link to single post returning 404.
I am using createPages API in gatsby-node.js How can I create page dynamically not just update data? Or I need to rebuild every times.
gatsby-node.js
const path = require(`path`)
const { slash } = require(`gatsby-core-utils`)
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
const result = await graphql(`
{
wpgraphql {
pages {
edges {
node {
title
databaseId
content
slug
id
}
}
}
posts {
edges {
node {
title
content
databaseId
slug
id
}
}
}
}
}
`)
const { pages, posts } = result.data.wpgraphql
const pageTemplate = path.resolve(`./src/templates/page.js`)
pages.edges.forEach(edge => {
createPage({
path: `/${edge.node.slug}/`,
component: slash(pageTemplate),
context: {
id: edge.node.id,
slug: edge.node.slug,
},
})
})
const postTemplate = path.resolve(`./src/templates/post.js`)
posts.edges.forEach(edge => {
createPage({
path: `/${edge.node.slug}/`,
component: slash(postTemplate),
context: {
id: edge.node.id,
slug: edge.node.slug,
},
})
})
}
component Posts
import React from 'react';
import gql from 'graphql-tag';
import { Query } from 'react-apollo';
import { Link } from "gatsby"
import parse from "html-react-parser";
const POSTS_QUERY = gql`
query MyQuery {
posts {
nodes {
title
content
id
slug
}
}
}
`;
class Posts extends React.Component {
// Render stuff.
render() {
return(
<Query query={POSTS_QUERY}>
{({ loading, error, data }) => {
if (loading) return 'Loading comments...';
if (error) return 'Error loading comments...';
return (
<div className="comment-list">
{data.posts.nodes.map((post) => (
<div key={post.id} className="comment">
<div className="comment-author">
<Link key={post.id} to={post.slug}>{post.title}</Link>
</div>
<div
className="comment-content"
dangerouslySetInnerHTML={{ __html: post.content }}
/>
</div>
))}
</div>
)
}}
</Query>
)
}
}
export default Posts;
index.js
import React, { Component } from "react"
import Layout from "../components/layout"
import Posts from "../components/posts";
const HomePage = () => {
return <>
<Layout>
<Posts></Posts>
</Layout>
</>
};
export default HomePage;
question from:
https://stackoverflow.com/questions/66049848/create-pages-dynamically-gatsby-and-apollo 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…