TypeError: Cannot read properties of null (reading 'useContext')
Unanswered
Laertes posted this in #help-forum
LaertesOP
I wrote a static page, the code here: https://github.com/MarsCoinToken/website when I run next build to compile his time, an error as shown
9 Replies
LaertesOP
i need help
Sun bear
read the error... some component in the page is trying to read a context that is null. You are probably not using context correctly somewhere in your page.
Sun bear
when creating a context:
// YourContext.tsx
// Define your context type and export the context component.
// Always Give relative information in default context value or use null.
type YourContextType = {
ContextState: string
onContextStateChange: Dispatch<SetStateAction<string>>
}
export const YourContext = createContext<ContextType | null>(null)// useYourContext.tsx
// Create a custom hook to easily access your context.
// This hook also handles if the context is undefined or null for you and makes the rest of the application typesafe by returning a sure context type and not null.
export default function useYourContext() {
const context = use(YourContext) // note: use useContext or new react use hook
if (!context) {
throw new Error("useYourContext must be used within a YourContext.Provider")
}
return context
}// now you can use this context without worrying
const {ContextState, onContextStateChange} = useYourContext()always use this pattern or something similar to ensure this error does not get caught in the build but instead in development if you are using typescript
LaertesOP
No, if you look at my code, it doesn't use useContext, it's very simple, just four widgets
😿
LaertesOP
help!
Toyger
your repo messed up, you have .next and .DS_Store here,
this error can be either nextjs version with or nodejs version, or your code,
you better create new nextjs repo with current stable version and with nodejs v20 LTS and then move your code in new project
this error can be either nextjs version with or nodejs version, or your code,
you better create new nextjs repo with current stable version and with nodejs v20 LTS and then move your code in new project
@Laertes help!
please only bump your post at most once a day