REQUEST A DEMO

Tag: react

Simplify Redux Actions with Middleware

December 14, 2015 Comparing Flux with Redux Working with React, we compared flux with redux, our team decided to use redux. The devtools redux offers was icing on the cake. Diving in, we wanted a central location for all of our API calls. The API middleware would need to handle dispatching a pre-request, successful request, and failures. To handle this, we set our actions in the following format Actions import DT_API_CALL from '../middleware/api'; const USER_REQUEST = 'USER_REQUEST'; const USER_SUCCESS = 'USER_SUCCESS'; export function fetchUser(userId) { return { [DT_API_CALL]: { types: [USER_REQUEST, USER_SUCCESS], endpoint: '/user/${userId}', method: 'get' } }; } export function saveUser(user) { return { [DT_API_CALL]: { types: [USER_REQUEST, USER_SUCCESS], endpoint: '/user/update', method: 'put', data: user } }; } Configure middleware Configuring our middleware looks something like: export default store => next => action => { const apiCall = action[DT_API_CALL]; if (typeof apiCall…