I created a user context in my App.js then I used context.provider to provide the context values to the children components. I can simply consume the context from the "login.js" component, but when I try to consume it from another component, it gives "undefined" Value.
Here is my App.js
import React, {createContext} from "react";
export const UserContext = createContext();
function App() {
const [loggedUser, setLoggedUser] = React.useState({});
const changeUserValue = (newValue)=>{
setLoggedUser(newValue);
}
return (
<Router>
<Switch>
<UserContext.Provider value={{loggedUser,changeUserValue}}>
<Route path="/" exact>
{loggedUser.username ? <Home /> : <Login />}
</Route >
<Route path="/home" exact>
{loggedUser.username ?
<Home />
:
<Login />}
</Route >
</UserContext.Provider>
</Switch >
<Footer />
</Router >
);
}
Here is my first component where I consumed the context in Login.jsx
import React, {useContext} from "react";
import UserContext from "../../App.js"
function Login(props) {
const {changeUserValue}= useContext(UserContext);
...
Axios(config)
.then(function(response) {
if(response.status===200){
changeUserValue(response.data);
localStorage.setItem("myUser", JSON.stringify(response.data));
}
})
.catch(function(error) {
setErrors([{code:"Credintials", text:error.message}])
});
And here is the other component "AdminControl.jsx" which gives the "undefined" value when consuming the context:
import React, {useContext} from "react";
import UserContext from "../../App.js"
function AdminControls(props){
const {user}=useContext(UserContext);
console.log(user);
...
Keep in mind that the last component is child for the component.