0

I'm adding some authorization checks to different pages in an app, but running into some errors passing down a piece of state.

I have

const RequireAuth = Component => {
  return class App extends React.Component {
    state = {
      isAuthenticated: false,
      isLoading: true
    };
    _updateLogin = () => {
      this.setState({ isAuthenticated: true, isLoading: false });
    };

    render() {
      const { isAuthenticated, isLoading } = this.state;
      if (isLoading) {
        return <div>Placeholder for animation</div>;
      }
      if (!isAuthenticated) {
        return <Redirect to="/auth/login-page" />;
      }
      return <Component {...this.props} />;
    }
  };
};

And I am trying to pass down the _updateLogin function to the AdminLayout component, where I have a login page.

ReactDOM.render(
  <Router history={hist}>
    <Switch>
      <Route
        path="/admin"
        component={RequireAuth(AdminLayout)}
        login={() => {this._updateLogin}}
      />
      <Route path="/auth" component={AuthLayout} />
      <Redirect from="/" to="/admin/dashboard" />
    </Switch>
  </Router>,
  document.getElementById("root")
);

If I run the above code, I get

  Line 43:23:  Expected an assignment or function call and instead saw an expression  no-unused-expressions

If I change the login to

login={this._updateLogin}

it returns

"Cannot read property '_updateLogin' of undefined.

Any tips?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
  • Something like: `` – Emile Bergeron Mar 02 '20 at 22:41
  • Also, take some time to really [understand context in JavaScript (`this`)](https://stackoverflow.com/q/20279484/1218980) as it'll save you a lot of time as you develop anything in JS. – Emile Bergeron Mar 02 '20 at 22:43
  • 1
    beyond what @EmileBergeron said, you are trying to define a `login` prop on a `Route` component that accesses the method of a component passed in the `component` prop (on the Route component). That wont do what you expect. What are you trying to accomplish here with that? – John Ruddell Mar 02 '20 at 22:52
  • @EmileBergeron thanks, will read that! – David Bolton Mar 02 '20 at 23:12
  • @JohnRuddell Just noticed that, definitely a big mistake on my part. – David Bolton Mar 02 '20 at 23:12
  • No worries we all make mistakes. What are you trying to do though? Maybe I can help you figure out a better implementation, but difficult without knowing what the goal is – John Ruddell Mar 02 '20 at 23:14

0 Answers0