Reputation: 1
I finished my first gatsby.js project and it runs with no error under "gatsby develop". However, when I run build command as: "gatsby clean && gatsby build", I am getting the following error:
failed Building static HTML for pages - 3.164s
ERROR #95313
Building static HTML failed for path "/lectures/lecture"
See our docs page for more info on this error: https://gatsby.dev/debug-html
4 |
5 | const Links = ({ styleClass, active, children }) => {
> 6 | const { user, setUser } = useContext(UserContext);
| ^
7 |
8 | let loggedInMenus = false;
9 |
WebpackError: TypeError: Cannot destructure property 'user' of 'Object(...)(...)' as it is null.
- links.js:6 Links
src/constants/links.js:6:11
not finished Generating image thumbnails - 22.034s
Now this is my link.js.
import React, { useContext } from 'react';
import { UserContext } from '../context/UserContext';
import { Link } from "gatsby"
const Links = ({ styleClass, active, children }) => {
const { user, setUser } = useContext(UserContext);
let loggedInMenus = false;
if (user && user.user.is_active) {
loggedInMenus = true;
}
return (
<ul className={styleClass}>
<li>
<Link to="/" className="page-link" active={active}>
Home
</Link>
</li>
<li>
{
(loggedInMenus !== true) ? (<></>) : (
<Link to="/lecture" className="page-link" active={active}>
Lectures
</Link>
)
}
</li>
</ul>
)
}
export default Links
In src > context > UserContext.js, I have this "user" state which is initially set to "null"
import React, { createContext, useState } from 'react'
export const UserContext = createContext(null);
export default ({ children }) => {
const [user, setUser] = useState(null);
return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
)
}
I guess that it doesn't like the "user" value is null when it's passed to Provider(?).
Any idea how to fix this build error please?
Upvotes: 0
Views: 861
Reputation: 41
You should not pass null
to Context
on this line:
export const UserContext = createContext(null);
Create a default context as followed:
const defaultContext = {
user: ''
};
Then assign the default context variable to createContext()
:
export const UserContext = createContext(defaultContext);
Upvotes: 2