24

The scenario is, I want to redirect a user or show alert based on the success, error callbacks after dispatching an action.

Below is the code using redux-thunk for the task

this.props.actions.login(credentials)
.then((success)=>redirectToHomePage)
.catch((error)=>alertError);

because the dispatch action in redux-thunk returns a Promise, It is easy to act with the response.

But now I'm getting my hands dirty on redux-saga, and trying to figure out how I can achieve the same result as above code. since Saga's run on a different thread, there is no way I can get the callback from the query above. so I just wanted to know how you guys do it. or whats the best way to deal with callbacks while using redux-saga ? the dispatch action looks like this :

this.props.actions.login(credentials);

and the saga

function* login(action) {
  try {
    const state = yield select();
    const token = state.authReducer.token;
    const response = yield call(API.login,action.params,token);
    yield put({type: ACTION_TYPES.LOGIN_SUCCESS, payload:response.data});
    yield call(setItem,AUTH_STORAGE_KEY,response.data.api_token);
  } catch (error) {
    yield put({type: ACTION_TYPES.LOGIN_FAILURE, error})
  }
}

saga monitor

export function* loginMonitor() {
  yield takeLatest(ACTION_TYPES.LOGIN_REQUEST,login);
}

action creator

function login(params) {
  return {
    type: ACTION_TYPES.LOGIN_REQUEST,
    params
  }
}
ZaL
  • 243
  • 1
  • 2
  • 5
  • redirectToHomePage can you please show me this method code because my app is not navigation to home page – rana_sadam Feb 22 '18 at 14:14
  • See https://stackoverflow.com/a/60638182/1056941 for my answer to a similar question, arranging for dispatch() to return a promise in redux-saga. – ronen Mar 11 '20 at 14:21

4 Answers4

17

I spent all day dinking around with this stuff, switching from thunk to redux-saga

I too have a lot of code that looks like this

this.props.actions.login(credentials)
.then((success)=>redirectToHomePage)
.catch((error)=>alertError);

its possible to use thunk + saga

function login(params) {
  return (dispatch) => {
    return new Promise((resolve, reject) => {
      dispatch({
        type: ACTION_TYPES.LOGIN_REQUEST,
        params,
        resolve, 
        reject
      })
    }
  }
}

then over in saga land you can just do something like

function* login(action) {
  let response = yourApi.request('http://www.urthing.com/login')
  if (response.success) {
    action.resolve(response.success) // or whatever
  } else { action.reject() }
}
James
  • 3,139
  • 2
  • 17
  • 22
12

I think you should add redirect and alert to the login generator. This way all logic is in the saga and it is still easily tested. So basically your login saga would look like this:

function* login(action) {
  try {
    const state = yield select();
    const token = state.authReducer.token;
    const response = yield call(API.login,action.params,token);
    yield put({type: ACTION_TYPES.LOGIN_SUCCESS, payload:response.data});
    yield call(setItem,AUTH_STORAGE_KEY,response.data.api_token);
    yield call(redirectToHomePage); // add this...
  } catch (error) {
    yield put({type: ACTION_TYPES.LOGIN_FAILURE, error});
    yield call(alertError); // and this
  }
}
Henrik R
  • 3,688
  • 1
  • 20
  • 22
  • Yes, this is what I ended up doing. Glad that we both opted out for same solution. Thanks – ZaL Dec 12 '16 at 07:39
  • 1
    Good to hear! Also if you want to accept the answer so other people can find it easily. – Henrik R Dec 12 '16 at 11:40
  • 1
    I'm using the same approach, but our app is huge and i'm facing some limitations... Depending on the component doing to action, different navigation should happen. At first I added navigateTo as a parameter to the action, but this does not work with e.g. NavigationActions.back(). Then the solution would be to add a callback to the action (you see where this is going...?). But of course callbacks should be replaced by promises... async-await... generators... saga's? – Thomas Stubbe Feb 20 '19 at 12:37
1

You can simply work up by passing the extra info about your success and error callback functions into the payload itself. Since, redux pattern works in a quite decoupled manner.

this.props.actions.login({
   credentials,
   successCb: success => redirectToHomePage)
   errorCb: error => alertError)
 });

In the saga, you can deconstruct these callbacks from the payload and run them very easily based on your program flow.

Param Singh
  • 1,037
  • 3
  • 11
  • 27
1

Your call:

this.props.addCutCallback(currentTime, callback);

Your mapping that you pass to connect() function:

const mapDispatchToProps = (dispatch) => ({
  addCutCallback: (time, callback) =>
    dispatch(ACTIONS.addCutCallback(time, callback)),
});

export default connect(mapStateToProps, mapDispatchToProps)(Home);

Your saga:

import {put, takeEvery, all, select} from 'redux-saga/effects';
import * as Actions from './../actions';

const getCuts = (state) => state.cuts;

function* addCutSaga({time, callback}) {
  yield put({type: Actions.ADD_CUT, time});
  const cuts = yield select(getCuts);
  callback(cuts);
}

function* cutsSaga() {
  yield takeEvery(Actions.ADD_CUT_CALLBACK, addCutSaga);
}

export default function* rootSaga() {
  yield all([cutsSaga()]);
}
Peter
  • 9
  • 2