Build fails if I try to get the length property of a string passed from parent through props.
Same error occurs localy and on netlify deploy.
TypeError: Cannot read property 'length' of undefined
$ gatsby new gatsby-starter-default https://github.com/gatsbyjs/gatsby-starter-default
// index.js
const IndexPage = () => {
const foo = 'Hello World'
return (
<Layout
foo={foo}
>
<h1>Hi people</h1>
</Layout>
)
}
// layout.js
const Layout = ({ children, foo }) => {
const bar = foo.length
{...}
}
$ yarn build
Build complete
failed Building static HTML for pages - 0.906s
ERROR #95313
Building static HTML failed for path "/404/"
See our docs page for more info on this error: https://gatsby.dev/debug-html
15 | const Layout = ({ children, foo }) => {
16 |
> 17 | const bar = foo.length
| ^
18 | console.log(foo, bar)
19 |
20 |
WebpackError: TypeError: Cannot read property 'length' of undefined
- layout.js:17 Layout
src/components/layout.js:17:20
error Command failed with exit code 1.
bash
System:
OS: Linux 4.15 Ubuntu 18.04.3 LTS (Bionic Beaver)
CPU: (4) x64 Intel(R) Core(TM) i5-7300HQ CPU @ 2.50GHz
Shell: 5.4.2 - /usr/bin/zsh
Binaries:
Node: 12.13.0 - ~/.nvm/versions/node/v12.13.0/bin/node
Yarn: 1.19.2 - /usr/bin/yarn
npm: 6.13.1 - ~/.nvm/versions/node/v12.13.0/bin/npm
Languages:
Python: 2.7.15+ - /usr/bin/python
Browsers:
Chrome: 78.0.3904.108
Firefox: 70.0.1
npmPackages:
gatsby: ^2.18.4 => 2.18.4
gatsby-image: ^2.2.34 => 2.2.34
gatsby-plugin-manifest: ^2.2.30 => 2.2.30
gatsby-plugin-offline: ^3.0.24 => 3.0.24
gatsby-plugin-react-helmet: ^3.1.16 => 3.1.16
gatsby-plugin-sharp: ^2.3.4 => 2.3.4
gatsby-source-filesystem: ^2.1.39 => 2.1.39
gatsby-transformer-sharp: ^2.3.6 => 2.3.6
npmGlobalPackages:
gatsby-cli: 2.8.14
Hi @calag4n, I don't know the exact reason why this is happening but seems like this issue is similar to the issue where window is not available during server side rendering (when gatsby build is run)
here's a work around :-
// layout.js
const Layout = ({ children, foo }) => {
const bar = foo && foo.length; // if foo exists then access foo.length;
}
https://github.com/gatsbyjs/gatsby/issues/309#issuecomment-223360361
Wow !
I stucked on this the entire last night, over-thinking some weird ways to fix it.
Then, barely two hours after I report that issue you come with the simpliest way to solve this ^^' .
I found out that is some others prototype methods wich end up the same error (like Array.slice()).
I love the open source community . And I love Gatsbyjs btw :)
You are welcome @calag4n :heart:
Great anuraghazra
Most helpful comment
Hi...
Wow !
I stucked on this the entire last night, over-thinking some weird ways to fix it.
Then, barely two hours after I report that issue you come with the simpliest way to solve this ^^' .
I found out that is some others prototype methods wich end up the same error (like
Array.slice()).Thank you very much @anuraghazra !
I love the open source community . And I love Gatsbyjs btw :)