Redux

Thunk

(Middleware)

Objectives

  • Define redux middleware

  • Define redux thunk and show a use case

Redux Middleware

Same idea as middleware in NodeJS

Code that is executed after an action is dispatched but before a reducer handles the action

Redux Thunk

Middleware for handling async actions

(API requests)

npm install --save redux-thunk

Middleware Setup

With Redux Thunk

import { createStore,
        applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { createLogger } from 'redux-logger'
import reducer from './reducers'

const middleware = [ thunk ]
if (process.env.NODE_ENV !== 'production') {
  middleware.push(createLogger())
}
const store = createStore(
  reducer,
  applyMiddleware(...middleware)
)

Thunk Action Creator

export const receivePosts = (reddit, json) => ({
  type: RECEIVE_POSTS,
  reddit,
  posts: json.data.children.map(child => child.data),
  receivedAt: Date.now()
}

const fetchPosts = reddit => (
  dispatch => {
    dispatch(requestPosts(reddit))
    return fetch(`https://www.reddit.com/r/${reddit}.json`)
      .then(response => response.json())
      .then(json => dispatch(receivePosts(reddit, json)))
  }
)

Redux Examples Async

Redux Thunk (Middleware)

By Elie Schoppik

Redux Thunk (Middleware)

  • 1,717
Loading comments...

More from Elie Schoppik