I want to login only when isLoggedIn is True, else it will be in the "/login". if isLoggedIn is True it should go to "/device"
I tried using the ternary operator but it not working, how can I use the Link to move different pages dynamically
So if I'm understanding your question correctly, you want a user to be able to click a "login" link and make a POST request to the "/api/userCheck" endpoint. Depending on the response you want to conditionally navigate to either "/devices" or to "/login" (stay on the same page).
For this you will need to prevent the default "action" of clicking the link from triggering the navigation and call the handleLoginClick callback, then issue an imperative navigation to the target route.
handleLoginClick(e) {
e.preventDefault();
const { pass, user } = this.state;
axios.post(
"http://localhost:3001/api/userCheck",
{ email: user, password: pass }
).then(res => {
if (res.data.login) {
this.setState({ fname: res.data.fname });
this.setState({ isLoggedIn: true });
localStorage.setItem('loginstatus', true);
this.props.history.replace("/device");
} else {
this.setState({ isLoggedIn: false });
this.props.history.replace("/login");
}
}).catch(err => {
this.setState({ isLoggedIn: false });
this.props.history.replace("/login");
});
}
Ensure the click event is passed to the callback.
<Link
onClick={this.handleLoginClick} // <-- set handleLoginClick directly as callback
to="/devices"
className="btn btn-pink my-3"
>
<i className="fas fa-lock"/>
Login
</Link>