Reputation: 1213
I have 2 contexts in my app.js
file:
function App() {
return (
<AuthContext>
<ChildContext>
<Template />
</ChildContext>
</AuthContext>
);
}
when the user logs out I want to access a value inside ChildContext
,but logout
function is inside AuthContext
:
// inside AuthContext:
const myContext = useContext(ChildContext);
const logout = () => {
// doing some stuff..
//
// here is the problem:
console.log(myContext.some_value);
}
the error is:
cannot read property 'some_value' of undefined
that's because ChildContext
is declared after AuthContext
.
so how can I get to some_value
inside AuthContext
?
Upvotes: 0
Views: 330
Reputation: 53874
In React the data flows down, so your options are:
ChildContext
to be a parent of AuthContext
.logout
function to its own contextfunction App() {
const logout = () => {
/*...*/
};
return (
<LogoutContext value={logout}>
<AuthContext>
<ChildContext>
<Template />
</ChildContext>
</AuthContext>
</LogoutContext>
);
}
Upvotes: 1