Async actions in Redux
Out-of-the-box, Redux is synchronous. If you try to dispatch an async function, you'll get an error:
Actions must be plain objects. Use custom middleware for async actions.
importthunk from 'redux-thunk' import createLogger from 'redux-logger' const middleware = [thunk] if (process.env.NODE_ENV !== 'production') { middleware.push(createLogger()) } const store = createStore(reducers, applyMiddleware(...middleware))
redux-thunk
is middleware that will allow us to dispatch a function and wait for the result; then we can dispatch another action(s).
Here's how we can use async actions:
export const track = filter => { return dispatch => { Meteor.call('track_phrase', filter.phrase, err => { if (!err) { dispatch(selectFilter(filter.id)); } //do something if you have an error. you can dispatch another action }) } }
In the action, we call a standard Meteor method by passing a filter phrase to the server...