I am trying to build a simple authentication system where the logged-in user’s username get saved in local storage. But I also want to save it in a state because pages will be rendered differently according to whether the user is logged in or not.
What I am trying to do is I have in my app.js a loggedUser state. I also created a context so that I can change that state from child components such as RegistrationForm
When I try to call UserContext i get that it is undefined. Do I need to export it to use it ? If yes, then what is the purpose of context provider and consumer.
This is my code for app.js
function App() {
//logged in user
const [loggedUser, setLoggedUser] = useState(null);
//create context for user
const UserContext = createContext({
loggedUser: null,
setLoggedUser: () => {},
});
//value that will be passed to the context
const value = {
loggedUser,
setLoggedUser,
};
//get the logged User if already exists
useEffect(() => {
setLoggedUser(localStorage.getItem("user"));
}, []);
.
.
.
return (
<UserContext.Provider value={value}>
.
.
.
</UserContext.Provider>
);
}
This is where I am calling the useContext and I get the error that UserContext is not defined
export default function RegistrationForm({ onClick }) {
const navigate = useNavigate();
const { setLoggedUser } = useContext(UserContext);
.
.
.
>Solution :
Please define the UserContext outside app.js and export it.
Then import the UserContext in the file where you want to use it.
export const UserContext = createContext({
loggedUser: null,
setLoggedUser: () => {},
});
function App() {
const [loggedUser, setLoggedUser] = useState(null);
... ... ...
}