Skip to content

Instantly share code, notes, and snippets.

@evturn
Created February 6, 2016 09:01
Show Gist options
  • Save evturn/b4f245658d58f6cc1978 to your computer and use it in GitHub Desktop.
Save evturn/b4f245658d58f6cc1978 to your computer and use it in GitHub Desktop.
Redux flow & asynchronicity
@evturn
Copy link
Author

evturn commented Feb 6, 2016

Redux

Actions

redux-thunk

By using this specific middleware, an action creator can return a function instead of an action object. This way, the action creator becomes a Thunk

  • When an action creator returns a function, that function will get executed by the Redux Thunk middleware.
  • This function doesn’t need to be pure. It can have side effects, including executing asynchronous API calls.
  • The function can also dispatch actions—like those synchronous actions
export function fetchPosts(subreddit) {

  // Thunk will pass the dispatch method as an argument 
  // to the function making it able to dispatch actions itself.
  return function (dispatch) {

    // First dispatch: the app state is updated 
    // to inform that the API call is starting.
    dispatch(requestPosts(subreddit))

    // The function called by the thunk can return a value
    // that is passed on as the return value of the dispatch method.

    // In this case, we return a promise to wait for.
    return fetch(`http://www.reddit.com/r/${subreddit}.json`)
      .then(response => response.json())
      .then(json =>

        // We can continue to dispatch many times.
        // Here we update the app state with the results of the API call.
        dispatch(receivePosts(subreddit, json))
      )
      .catch(error => console.log(error))
  }
}

Middleware

redux

Redux middleware solves different problems than Express or Koa middleware, but in a conceptually similar way. It provides a third-party extension point between dispatching an action, and the moment it reaches the reducer. People use Redux middleware for logging, crash reporting, talking to an asynchronous API, routing, etc.

Without middleware, Redux store only supports synchronous data flow. This is what you get by default with createStore()

  • You may enhance createStore() with applyMiddleware()
  • Use the applyMiddleware() store enhancer from Redux to include the Redux Thunk middleware in the dispatch mechanism.
  • Asynchronous middleware like redux-thunk or redux-promise wraps the store’s dispatch() method and allows you to dispatch something other than actions, for example, functions or Promises.
  • Any middleware you use can then interpret anything you dispatch and pass actions to the next chain of middleware.
  • When the last middleware in the chain dispatches an action, it has to be a plain object.
import thunkMiddleware from 'redux-thunk'
import createLogger from 'redux-logger'
import { createStore, applyMiddleware } from 'redux'
import { selectSubreddit, fetchPosts } from './actions'
import rootReducer from './reducers'

const loggerMiddleware = createLogger()

const store = createStore(
  rootReducer,
  applyMiddleware(
    thunkMiddleware, // to dispatch() functions
    loggerMiddleware // to log actions
  )
)

store.dispatch(selectSubreddit('reactjs'))
store.dispatch(fetchPosts('reactjs')).then(() =>
  console.log(store.getState())
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment