0

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:

  1. user enter username and password and clicking a submit
  2. handle submit fires action method called onAuth(authLogin)
  3. 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,
    

    } ; };

1 Answer 1

0

Think the to handle with this issue is using setTimeout function of the redirect function

setTimeout(() => {
    // redirecting function call
   }, 3000);

That fixed it for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.