Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Build Applications with Meteor

You're reading from   Build Applications with Meteor Isomorphic JavaScript web development

Arrow left icon
Product type Paperback
Published in May 2017
Publisher Packt
ISBN-13 9781787129887
Length 388 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Dobrin Ganev Dobrin Ganev
Author Profile Icon Dobrin Ganev
Dobrin Ganev
Arrow right icon
View More author details
Toc

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...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime