简体   繁体   中英

How to dispatch an action(Redux) after redirection is done?

I'm trying to make a Loading spinner keep showing as long as the facebook authentication is on progress. And hide the loading spinner when the request + page redirection is done.

In this case authenticating facebook could be done by clicking login button after that the browser will redirecting to http://localhost:3000/auth/facebook .

Here is what i have tried so far.

I made a reducer to store the loading state that i can override later using an action.

dispatch(itemsIsLoading(true));

Redux state tree :

{
  ...
  isLoading: loadingReducer
}

Here is the code for the action.

export const requestLogin = ({ username, password }, callback) => async dispatch => {
  // Show the loading spinner
    dispatch(itemsIsLoading(true));

  const res = await axios.post('/api/authenticate', {
    username,
    password
  });

  dispatch({ type: REQUEST_LOGIN, payload: res.data });

  // Redirect to/auth/facebook after login amember is success
  callback();

  // Stop spinner and show the content
  dispatch(itemsIsLoading(false));
};

 export function itemsIsLoading(bool) {
  return {
    type: ITEMS_IS_LOADING,
    isLoading: bool
  };
}

Here is the method that i use after login form was submitted

 onFormSubmit = async (e) => {
    e.preventDefault();

    let dataLogin = {
      username: this.username.value.trim(),
      password: this.password.value.trim(),
    }

    this.props.requestLogin(dataLogin, () => {
      switch (this.props.auth) {
        case 1:
          this.props.redirect(true, '/auth/facebook');
          break;
        case 2:
          toast.warn('Your license is expired. Contact iqbal bro');
          break;
        case 3:
          toast.error('Username or password is not match');
          break;
        default:
          console.log('Something is wrong, please contact administrator');
      }
    });
  }

My question is how to dispatch an action after the page redirection is done. Because using the above code the spinner will immediately stop after the request was resolved and doesn't care with the redirecting process.

With my answer I am assuming that you have control over the component that renders after redirection. If this is the case you can simply put dispatch(itemsIsLoading(false)) inside componentDidMount hook of the component that renders immediately after redirection. Inside requestLogin you can do something like this:

  .
  .
  .
  callback();

  if(!res.data.successfulAuth) {
    dispatch(itemsIsLoading(false));
  }
};


Hope this solves your problem!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM