I'm trying to figure out how to set my user state with react hooks after an axois post request. Struggling to find a good solution. I've read the react hooks documentation and almost all examples that I find are just when the page loads. I want to setState on form submission as the user logs in.
Login.js
const handleLogin = (evt) => {
//Prevent default form submission
evt.preventDefault();
const loginDetails = {
username: username,
password: password,
}
//send login request to api
axios.post('http://localhost:5000/users/login', loginDetails)
.then((res) => {
setUser(loginDetails.username);
history.push('/');
})
.catch((err) => {
console.log('incorrect password/user');
history.push('/login');
})
}
Due to the Asynchronous behaviour the state is not being set before the redirect. I have also tried to place the redirect in a useEffect, but it constantly reloads the page, even when I past in a dependency. How to I ensure that my state is being set, passed into my navbar component as a prop before the history.push('/')
takes effect.
Edit
App.js
return (
<Router history={history} >
<div className={styles.app}>
<Navbar user={user}/>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route exact path="/blog" component={Blog}/>
<Route exact path="/blog/create" component={CreateBlog}/>
<Route exact path="/blog/:id" component={ViewBlog}/>
<Route path="/demo" component={Demo}/>
<Route path='/resume' component={Resume}/>
<Route
exact path="/login"
render={(props) => (
<Login loginHandler={handleLogin}
usernameHandler={onChangeUsername}
passwordHandler={onChangePassword}/>)}
/>
<Route exact path="/register" render={(props) => (
<Register usernameHandler={onChangeUsername}
passwordHandler={onChangePassword}
handleRegister={handleRegister}/>
)}/>
</Switch>
<Footer/>
</div>
</Router>
);
}
export default App;