0

I am creating pages dynamically with gatsby-node.js file

let allProducts = result.data.allProducts.edges
    createPage({
        path: `/products`,
        component: require.resolve('./src/pages/products.js'),
        context: { allProducts }
    });

  //Create a page for each Product.
  allProducts.map((edge)=>{
    let product = edge.node
    createPage({
      path:`/product/${product.id}`,
      component: require.resolve('./src/pages/product.js'),
      context:{product}
    })
  })

Gatsby develop is running fine but when i do gatsby build it gives error

error Building static HTML for pages failed

See our docs page on debugging HTML builds for help https://gatsby.app/debug-html

  43 |         <div >
  44 |             <Img fluid={data.bannerHeaderProduct.childImageSharp.fluid}/>
> 45 |             <img src={product.imgSrc }alt=""/>
     |                               ^
  46 |         </div>
  47 |         <div>
  48 |             <h3 dangerouslySetInnerHTML={{__html:product.name}}>

WebpackError: TypeError: Cannot read property 'imgSrc' of undefined

product which i am passing as context to pages is getting undefined

2 Answers 2

3

A simple fix is to rename pages folder to templates (and also change it in the paths in gatsby-node)

2
  • Also had this problem while using gatsby-plugin-create-client-paths and the fix (despite it working in development and having worked in a previous build afaik) was to move the file from the pages to the templates folder
    – Meiogordo
    Commented Jun 24, 2019 at 1:19
  • explanation: pages in src/pages are consumed by default, when reusing the files from this directory it get called multiple times and plus the one automatic
    – muescha
    Commented Jun 6, 2020 at 1:40
2

Seeing your code, it would work fine. the createPage structure is ok.

In my experience, Sometimes gatsby/graphql error emitter doesn't show the correct error line, if there're many variables with the same name (imgSrc) gatsby error emitter shows the first one appeared variable, not the wrong one.

To confirm that you should put an "if" before return the render checking if product is not defined. It is a good way to prevent render errors during builds:

render(){
   const {product} = this.props.pathContext;

   if(product === undefined) return null;

   ......

   return <div>....</div>;
}

You can also put a console.log in the gatsby-node showing "allProducts" & "product" variables, checking the variable structure during the build.

Could you please reply with the results?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.