0

I don’t know why I can read this pageContext array content only locally but not on build

I can access to the entire array but I can’t access to the single element inside id:

2:09:56 PM: error Cannot read properties of undefined (reading '0')
2:09:56 PM:   TypeError: Cannot read properties of undefined (reading '0')

indexTemplate.js

import React, {useState} from 'react'
import Layout from "../../components/Layout"


const IndexPage = ({data, pageContext}) => {
  const sliderRef = useRef();
  const {slideshow} = pageContext;
    return (
      <Layout >
          {typeof slideshow} 
/*
output:

Array(3)
   0: {duration: 4}
   1: {duration: 3}
   2: {duration: 2}
length: 3
[[Prototype]]: Array(0)
*/
         {typeof slideshow[0].duration}
/*
on NETLIFY build:
TypeError: Cannot read properties of undefined (reading '0')
*/

      </Layout>
    )
  }
export default IndexPage;

p.s. locally it works

2 Answers2

1

Try it like this:

const IndexPage = ({data, pageContext}) => {
  const sliderRef = useRef();
  const { slideshow= [] } = pageContext;
    return (
      <Layout>

My guess it's that the code is accessing pageContext when it's fully not hydrated with slideshow data. Adding a default value (empty array, []) can bypass it while the context is being filled with the proper data. I'd need more context to understand what's going on exactly.


It's unclear for me if it does, or it doesn't work locally. However, if it only works in gatsby develop it means that it doesn't work. You need to be sure that works under gatsby build too to ensure that "it works", otherwise, your code is only working under certain conditions but not in the whole scope of Gatsby.

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
  • Thank you for the question but the problem was more stupid than that. The problem was that I use Gatsby for this project and that file was in /pages directory. `- src` `- - pages` `- - - myfile.js` pages directory work in development mode in build mode works only if page file are in * */template** or different folder: `- src` `- - pages` `- - - .md files` `- - templates` `- - - page.js fies` – consciousOutsider Aug 10 '22 at 05:43
0

The problem was that I use Gatsby for this project and that file was in /pages directory.

src  
└───pages
│   │   index.md
│   │   index.js 

pages directory work in development mode in build mode works only if page files are in /template or different folder:

src  
└───pages
│   │   index.md
└───templates
    │   index.js