looshi / redux-ddp

Meteor app which uses DDP messages to populate a Redux store.
37 stars 2 forks source link

use redux thunk for any action that needs to call dispatch/access current state/calling remote api #2

Open looshi opened 8 years ago

looshi commented 8 years ago

From @sikanhe notes :

you have some side effects in this action creator

Actions.updateScore = function updateScore(playerId, playerName) {
  Meteor.call('players.update-score', playerId, function(err,res){
    if(err){
      Store.dispatch(Actions.updateScoreFailed(playerId, playerName));
    }else{
      Store.dispatch(Actions.updateScoreOk(playerId, playerName));
    }
  });
  return {
    type: 'UPDATE_SCORE',
    playerId: playerId
  };
};

and you’re using store.dispatch i recommend using redux thunk for any action that needs to call dispatch/access current state/calling remote api so with redux thunk, you will be able to do this

export function someActionCreator(data) {
  return (dispatch, getState) => {
    const somethingFromCurrentState = getState().something;

    Api.doSomethingRemote(something, (err, res) => {
      if(err) {
        dispatch(failed())
      } else {
        dispatch(success())
      }
    });
  }
}
sikanhe commented 8 years ago

The key benefit here is that you get dispatch and getState functions as params, this avoid the need to keep the Store object around. The "thunk" middleware will see you are returning a thunk instead of a normal action, it will pass the dispatch and getState functions to that function, and it just works. However, this is purely optional.

https://github.com/gaearon/redux-thunk