Using Redux middleware is the standard practice in the Redux world if you want to cause side-effects. I am simply echoing Dan Abramov in his guide. A standard action creator should not cause any side effects. If you want side-effects (aka asynchronous actions), use redux-thunk
or redux-promise
; redux-thunk
is just 8 lines of code.
You’ll also notice that there are usually three standard actions you dispatch in an async action creator. One to indicate you’re fetching (loading…), one to feed the results (success) or one to feed the error (fail).
Also, I think the most important reason to use redux-thunk
is that it allows you to access the entire state. Chances are, you’re going to need something in the state that you don’t immediately have access to when you call the action.
export function asyncComplexAction = () => (dispatch, getState) => {
const { somethingElse, andThis } = getState();
Meteor.call('something.using', somethingElse, andThis, error => {
dispatch({ type: 'OK' });
});
};
To somewhat escape callback hell, you can implement a promise-based redux-thunk
like:
export function deletePlayer = playerId => dispatch => new Promise((resolve, reject) => {
Meteor.call('players.delete', playerId, error => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
This allows you to chain your dispatches like:
dispatch(deletePlayer('1'))
.then(/* dispatch something else?... */)
.then(/* etc... */);
See Dan Abramov’s example code.
The reason for you should use promises is because you’ll eventually be able to take advantage of async
and await
(they will be available in Meteor soon I think), which will completely get rid of callback hell while preserving asynchronous execution.
There’s not a lot of documentation on the Meteor.connection.registerStore
API really. I would need to read the code and its comments, which I started doing. I’ll play around and see what I come up with.