Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gatsby works fine during development but throws error during build

I am passing data from one page to another in gatsby. First page code:

let state = {book: book, src: src}
return (
<div className="book__holder">
    <Link to="/pdf/" state={state}>
    <Card
        hoverable
        style={{ width: 240 }}
        cover={<img alt={book} 
                    src={url}
                    />}
        >
        <Meta
            title={book}
            description={faculty+" "+year+"-"+part}
        />
    </Card> 
    </Link> 
</div>

This data is used in pdf page as:

const PDFPage = props =>{
    return (
      <React.Fragment>
       <SEO title={props.location.state.book} />
       <NavBar></NavBar>
       <Embed src={props.location.state.src} type="application/pdf">
       </Embed>

     </React.Fragment>
    )}

export default PDFPage

Everything is fine when using gatsby develop but when i use gatsby build it throws following error:

error Building static HTML for pages failed

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

  11 |   return (
  12 |   <React.Fragment>
> 13 |     <SEO title={props.location.state.book} keywords={[`gatsby`,  
           `application`, `react`]} />
     |                                      ^
  14 |     <NavBar></NavBar>
  15 |     <Embed src={props.location.state.src} type="application/pdf">    
           </Embed>
  16 | 


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

        - pdf.js:13 PDFPage
         lib/src/pages/pdf.js:13:38

Can anyone help me please?

like image 969
codedump Avatar asked Mar 05 '23 15:03

codedump


1 Answers

Gatsby will throw error during production build, since location is not available during server-side rendering.

One way to make sure the build doesn't throw an error is to:

  1. Check for the window in componentDidMount
  2. Map the location prop to state
  3. Render the value from your state instead of directly from props

In componentDidMount()

componentDidMount() {
  if (typeof window === 'undefined') {
    return;
  }
  this.setState(() => ({ playerName: this.props.location.state.playerName }));
}

In render()

render() {
  return <div>{this.state.playerName}</div>;
}

credit to this thread, How to get previous url in react gatsby

like image 58
Vien Tang Avatar answered Apr 30 '23 06:04

Vien Tang