How to wrap React's Context Provider in NextJs
Unanswered
Masai Lion posted this in #help-forum
Masai LionOP
where to wrap Context Provider ?_app.jsx tried but errors come
31 Replies
Masai LionOP
hello @joulev !
this is the error
Uncaught TypeError: Cannot read properties of null (reading 'useContext')
at Object.useContext
this is the error
Uncaught TypeError: Cannot read properties of null (reading 'useContext')
at Object.useContext
import React, { createContext, useEffect, useState } from "react";
export const UserContext = React.createContext();
export const UserContextProvider = ({ children }) => {
const [user, setUser] = useState("sd");
useEffect(() => {
const storedUser = localStorage.getItem("user");
if (storedUser) {
try {
const parsedUser = JSON.parse(storedUser);
setUser(parsedUser);
} catch (error) {
console.error("Error parsing user data:", error);
localStorage.removeItem("user");
}
}
}, []);
const updateUser = (newUserData) => {
setUser(newUserData);
localStorage.setItem("user", JSON.stringify(newUserData));
};
const userId = user ? user.id : null;
return (
<UserContext.Provider value={{ user, updateUser, userId }}>
{children}
</UserContext.Provider>
);
};do you think there an error in my userContextProvider ?
@Masai Lion hello <@484037068239142956> !
this is the error
Uncaught TypeError: Cannot read properties of null (reading 'useContext')
at Object.useContext
what _app file is it? is it pages/_app or app/_app
Masai LionOP
pages/_app
it is
Masai LionOP
i am using src /components/navbar.js
in this i am trying to consume
where do you use that navbar
basically, do you use the context inside app/ directory?
@joulev where do you use that navbar
Masai LionOP
addproductspage.js inside this
@joulev basically, do you use the context inside app/ directory?
Masai LionOP
no i am using src without app directory
@Masai Lion hello <@484037068239142956> !
this is the error
Uncaught TypeError: Cannot read properties of null (reading 'useContext')
at Object.useContext
give me the full error trace stack of this error
Masai LionOP
hmmmmm this doesn't reveal any helpful info
make a reproduction repository
@joulev make a reproduction repository
Masai LionOP
meaning i should upload code to github right ?
upload a minimal version of your code that can reproduce the problem to a public place e.g. github
so i can clone it and run it locally
@joulev so i can clone it and run it locally
Masai LionOP
ya doing it right away 2mins
@joulev reposistory link https://github.com/aklite/nextjs-ecommerce
there are too many issues with your code: plenty of missing dependencies. also don't use
react-router-dom with nextjs since nextjs brings its own router and they clashfix them first then i'll have a look at the error above
@joulev fix them first then i'll have a look at the error above
Masai LionOP
okay @joulev