index.jsx
index.jsx

Reputation: 163

Gatsby to generate pages when a new variable is served from Contentful CMS

So I built a Gatsby blog with products, and it can programmatically generate pages for every product. I want to add to this project so that it also generates pages for product categories. Each category page will display all products in that category. The content is served from Contentful CMS.

Is this possible? to add a second layout template and create such pages?

exports.createPages = ({ graphql, boundActionCreators }) => {
    const { createPage } = boundActionCreators

    return new Promise((resolve, reject) => {
        const blogPost = path.resolve('./src/templates/blog-post.js')
        const categoryPage = path.resolve('./src/templates/category-post.js')

        resolve(
            graphql(
                `
            {
              allContentfulBlog(limit: 200) {
                edges {
                  node {
                    id
                    categories
                    mainTitle
                    mainImg {
                      id
                    }
                    mainText {
                      childMarkdownRemark {
                        excerpt
                      }
                    }
                    slug
                  }
                }
              }
            }
          `
            )
                .then(result => {
                    if (result.errors) {
                        console.log(result.errors)
                        reject(result.errors)
                    }

                    result.data.allContentfulBlog.edges.forEach(edge => {
                        createPage({
                            path: edge.node.slug,
                            component: blogPost,
                            context: {
                                slug: edge.node.slug,
                            },
                        })
                    })
                    return
                })
                .then(result => {
                    result.forEach(category => {
                        createPage({
                            path: '/' + edge.node.category,
                            component: categoryPage,
                            context: {
                                slug: edge.node.category,
                            },
                        })
                    })
                })
        )
    })
}

The first .then() method in the promise works just fine, and my idea is to simply add a second .then(), with the categories pages's template.

Terminal shows: terminal

Upvotes: 0

Views: 164

Answers (1)

xadm
xadm

Reputation: 8418

You could insert this after products pages loop but you don't have data for categories. It's possible to collect it from products but it would be quirky workaround.

You need separate query, separate promise and to compose promises (.all()) at top level.

Upvotes: 1

Related Questions