gatsby: Building static HTML failed when you createContext with empty default value
Description
It’s working when gatsby develop
but failed to build when you use React.createContext with empty default value
You can solve it by assigned default value in React.createContext method. But I cannot modify other npm packages which are using React.createContext with empty default value. So I cannot build the website.
Usually I set the default value by <Context.Provider value={defaultValue} children={children} />,
not in the createContext method
Steps to reproduce
Parent file const AppContext = React.createContext(); … <AppContext.Provider value={defaultValue} children={children} /> … … Children file const {isLogin} = React.useContext(AppContext);
or git clone https://github.com/codingfunwoody/reproduceGastby.git gatsby build
Expected result
Build successful
Actual result
WebpackError: TypeError: Cannot read property ‘isLogin’ of undefined
Environment
System: OS: Windows 10 CPU: (4) x64 Intel® Core™ i5-7200U CPU @ 2.50GHz Binaries: Yarn: 1.12.3 - C:\Program Files (x86)\Yarn\bin\yarn.CMD npm: 6.4.1 - C:\Program Files\nodejs\npm.CMD Browsers: Edge: 42.17134.1.0 npmPackages: gatsby: ^2.1.18 => 2.1.18 gatsby-plugin-create-client-paths: ^2.0.4 => 2.0.4 gatsby-plugin-react-helmet: ^3.0.6 => 3.0.7 gatsby-plugin-typescript: ^2.0.7 => 2.0.9
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 5
- Comments: 18 (5 by maintainers)
I had the same issue and solved it with a simple solution after some trial and error. My site would work fine with
gatsby develop
but failed usinggatsby build
with the error: “WebpackError: TypeError: Cannot read property of undefined”.To fix it, I added a
const initialState
object with the default values used for the context and passed that to thecreateContext
method like so:React.createContext(initialState)
. Build worked fine after that.I have the same issue on my project. Everything works fine when “gatsby develop”, but “gatsby build” fails.
I was able to “work around” the issue by using ||
This is not fixed and the above “fixes” are painful. The whole point of React context is so you don’t have to repeat that info every time you
useContext
down the tree.