pedram afra
pedram afra

Reputation: 1213

react use context value inside a parent context

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

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53874

In React the data flows down, so your options are:

  1. ChildContext to be a parent of AuthContext.
  2. Move logout function to its own context
function App() {
  const logout = () => {
    /*...*/
  };
  return (
    <LogoutContext value={logout}>
      <AuthContext>
        <ChildContext>
          <Template />
        </ChildContext>
      </AuthContext>
    </LogoutContext>
  );
}

Upvotes: 1

Related Questions