Mukesh Kumar
Mukesh Kumar

Reputation: 952

Gatsby develop command runs but gatsby build gives error

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

Upvotes: 0

Views: 2109

Answers (2)

Mukesh Kumar
Mukesh Kumar

Reputation: 952

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

Upvotes: 3

Situ
Situ

Reputation: 102

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?

Upvotes: 2

Related Questions