Pass object to child then access object methods

Viewed 44

So I have a file routes.jsx which handles the routing of my application. Following the docs for react-router-dom, I wanted to start working on login/logout.

For now, I have implemented a fakeAuth object which will authenticate against the backend and set an isAuthenticated var. However, I think I need to be able to pass this auth around to different components, such as the Login.jsx to actually change the state of isAuthenticated, and to let's say a NavBar.jsx so I can change a login button to a logout button (to clarify, all my components are functional components (trying) using hooks and do not extend React.Component in a class manner).

However, how do I pass the fakeAuth as a prop and still have access to the methods inside? If I declare fakeAuth inside the Login.jsx component, fakeAuth is defined. If I pass it in as a prop, it is considered not defined.

routes.js

export default (
  <BrowserRouter>
    <Route path='/'>
      <LandingPage fakeAuth={fakeAuth}/>  // Landing page has the NavBar component as a child.
    </Route>

    <Switch>
      <Route path="/login">
         <Login fakeAuth={fakeAuth}/> // I want the Login component to have access to fakeAuth.whatever
      </Route>
      <PrivateRoute path="/home">
        <UserApp/>
      </PrivateRoute>
    </Switch>
  </BrowserRouter>
);

const fakeAuth = {
  isAuthenticated: false,
  authenticate(cb) {
    fakeAuth.isAuthenticated = true;
    setTimeout(cb, 100); // fake async
  },
  signout(cb) {
    fakeAuth.isAuthenticated = false;
    setTimeout(cb, 100);
  }
};

Login.jsx

const Login = ({fakeAuth}) => {
  let history = useHistory();
  let location = useLocation();

  let { from } = location.state || { from: { pathname: "/home" } };
  let login = () => {
    fakeAuth.authenticate(() => {   // Need to access authenticate.
      history.replace(from);
    }); 
  };
  return (
    // login modal etc
    <button onClick={login}>Log in</button>
  );
}

The above code is the code that returns fakeAuth is undefined.

Any advice would be great!

0 Answers
Related