Search code examples
reactjsreact-fullstackreact-routing

React.js Render App.js after succesful Login


When an User succesfully is logged in through LoginForm.js

LoginForm.js

  ----constructor, etc.----
  }resetForm() {
    this.setState({
      //bla bla
    });
  }doLogin() {
    if (!this.state.email) {
      console.log("'Email' darf nicht leer sein");
      return;
    }
    if (!this.state.password) {
      console.log("'Passwort' darf nicht leer sein");
      return;
    }
    this.setState({
      buttonDisabled: true,
    });axios.post(
        "http://localhost:8080/api/login",
        {
          userEmail: this.state.email,
          userPassword: this.state.password,
        },
        {
          withCredentials: true, //ein Cookie wird gesetzt
        }
      ).then((response) => {
        if (response.data != -1) {
          console.log("login erfolgreich", response);
          UserStore.isLoggedIn = true;
          UserStore.id = response.data; //current user id wird zugewiesen
          UserStore.email = this.state.email;
          console.log("current_user_id: " + UserStore.id);
          this.resetForm();
          this.showCalendar();
        } else {
          console.log("login fehlgeschlagen", response);
          this.resetForm();
        }
      })
      .catch((error) => {
        console.log("API-Call fehlgeschlagen", error);
        this.resetForm();
      });
  }render() {
    return (
      <div className="loginForm">
        <Header name="Login" />
        <InputField
          type="email"
          placeholder="Email"
          value={this.state.email ? this.state.email : ""}
          onChange={(value) => this.setInputValue("email", value)}
        />
        <InputField
          type="password"
          placeholder="Password"
          value={this.state.password ? this.state.password : ""}
          onChange={(value) => this.setInputValue("password", value)}
        />
        <SubmitButton
          text="Login"
          disabled={this.state.buttonDisabled}
          onClick={() => this.doLogin()}
        />
      </div>
    );
  }
} ```

I want to render the page to <Calendar /> (Component Class Calendar.js). So that the user gets the main page of the application. 

I dont know, how i can get back to App.js to render the page, after getting the response "true" from the backend (--> Login Succesful).

I tried it with
``` showCalendar() {
    React.render(<Calendar/>);
  } ```

but it doesnt work.

UserStore.js
```class UserStore {
  constructor() {
    extendObservable(this, {
      isLoggedIn: false,
      email: "",
      userName: "",
      id: 0,
    });
  }
}```

export default new UserStore();
App.js
``` class App extends React.Component {
  componentDidMount() {
    
  }

  render() {
    return (
      <Router>
        <div>
          <nav>
            <ul>
              <li>
                <Link to="/">Home</Link>
              </li>
              <li>
                <Link to="/calendar">Calendar</Link>
              </li>
              <li>
                <Link to="/userlist">Userlist</Link>
              </li>
            </ul>
          </nav>

          {/* A <Switch> looks through its children <Route>s and
                renders the first one that matches the current URL. */}
          <Switch>
            <Route path="/calendar">
              <Calendar />
            </Route>
            <Route path="/userlist">
              <UserList />
            </Route>
            <Route path="/">
              <Home />
            </Route>
          </Switch>
        </div>
      </Router>
    );
  }
}

export default App;

ReactDOM.render(<App />, document.querySelector("#app"));

In my research in the internet i didnt found a solution to that. In my eyes there must be a way to add an eventlistener to the Userstore.id. So if the UserStore.id changes (happens when user logs in), we can rearrange the page to .


Solution

  • This is all you need to do: please separate the LoginForm.js file to a separate file.

    Import the withRouter

    import { withRouter } from 'react-router'
    

    then change your showCalendar to be like this:

    showCalendar() {
        const { history: { push } } = this.props;
        push('/calendar');
    }
    

    and don't forget to wrap your component in withRouter as well:

    export default withRouter(LoginForm);