So i'm trying to apply a simple login functionality using react, redux. By using axios post request sending to a django server (username, password) But the problem is from the component its been called from. For example component A. So scenario is like this:
- user enter username and password and clicking a submit
- handle submit fires action method called onAuth(authLogin)
- authLogin updating the state if successded or not
the problem is that the state is being updated to slow and state.error has no value which makes me redirecting the user somewhere when he didn't enter valid username,pass How can wait for the axios call to finish and wait for state update?
class A extends Component{ handleSubmit = (values) => { this.props.onAuth(values.username, values.password); if(!this.props.error){ // redirecting somewherr }else{ // giving error message } } render() { return{ <Form onSubmit={this.handleSubmit}> <Input name="username"/> <Input name="password"/> </Form> } } const mapStateToProps = (state) => { return { error: state.error, }; }; const mapDispatchToProps = (dispatch) => { return { onAuth: (username, password) => dispatch(actions.authLogin(username,password)), }; };
export default connect(mapStateToProps, mapDispatchToProps)(LoginView);
}
My initial state
const initialState = { token: null, error: null, loading: false, };
Login action
export const authLogin = (username, password) => { return (dispatch) => { dispatch(authStart()); axios .post("http://127.0.0.1:8000/login/", { username: username, password: password, }) .then((res) => { // some more code here dispatch(authSuccess(token)); }) .catch((err) => { dispatch(authFail(err)); }); };
};
authFail action
export const authFail = (error) => { return { type: actionTypes.AUTH_FAIL, error: error,
} ; };