Home > Software design >  Use an Saga action as condition for an if statement
Use an Saga action as condition for an if statement

Time:05-23

I'm actually trying to implement redux-saga into my app. To keep it easy in the beginning, I tried to add saga into my login component first.

But I'm struggling rn by adding an if statement which redirects the UI to an page if my login action loginSuccess() is dispatched. I would like to implement smth like the commented statement below:

  const onSubmitForm = (e?: React.FormEvent<HTMLFormElement>) => {
    if (e) {
      e.preventDefault();
    }
    dispatch(actions.submitLogin());

    // if (actions.loginSuccess() && !actions.loginError) {
    //  history.push('/');
    // }
  };


How the actions are passed:

   // After the API was fetched:
   if (response.message === 'login') {
      yield put(actions.loginSuccess());
    } else {
      yield put(actions.loginError('Username or password is incorrect'));
    }

CodePudding user response:

You would handle the "loginSuccess" action in your reducer to change your state, or possibly by another saga listening for the loginSuccess action to perform various other actions when the user logs in. e.g. fetching user data, redirecting the location, etc.

  • Related