Last active
March 27, 2016 20:34
-
-
Save eagsalazar/56bc0ce04fadc81ac9da to your computer and use it in GitHub Desktop.
Async middleware with Redux example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const getFeedItem = feedItemId => ( | |
{ | |
type: GET_FEED_ITEM, | |
ajax: true, | |
payload: { | |
type: 'get', | |
route: `/feed/${feedItemId}`, | |
pending: GET_FEED_ITEM_PENDING, | |
success: GET_FEED_ITEM_SUCCESS, | |
failure: GET_FEED_ITEM_FAILURE, | |
}, | |
} | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import superagent from 'superagent' | |
import Immutable from 'immutable' | |
const { API_BASE_URL } = __ENV__ | |
const API_VERSION = '/api/v1' | |
const API_URL = API_BASE_URL + API_VERSION | |
let responseCache = Immutable.Map() | |
const stringifiedQuery = query => query ? JSON.stringify(query) : '' | |
const responseFromCache = (route, query) => ( | |
responseCache.get(`${route}${stringifiedQuery(query)}`) || Immutable.Map() | |
) | |
const cacheResponse = (response, route, query) => ( | |
responseCache = responseCache.set( | |
`${route}${stringifiedQuery(query)}`, | |
Immutable.fromJS(response.body) | |
) | |
) | |
export default () => next => action => { | |
const { ajax, cache } = action | |
if (!ajax) return next(action) | |
const ajaxTypes = { | |
get: superagent.get, | |
post: superagent.post, | |
put: superagent.put, | |
} | |
const { pending, success, failure, route, query, body } = action.payload | |
next({ | |
type: pending, | |
payload: cache ? responseFromCache(route, query) : Immutable.fromJS(body || {}), | |
}) | |
return ajaxTypes[action.payload.type.toLowerCase()](API_URL + route) | |
.set('authorization', `Bearer ${window.sessionStorage.getItem('token')}`) | |
.query(query) | |
.send(body) | |
.end((err, response) => { | |
if (err) { | |
next({ | |
type: failure, | |
}) | |
} else { | |
if (cache) cacheResponse(response, route, query) | |
next({ | |
type: success, | |
payload: Immutable.fromJS(response.body), | |
}) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Q: Hey would you say using redux-thunk represents your latest and greatest take on async behavior that changes state on the server and the client?
A: redux-thunk is good, but these days I prefer to make a custom redux middleware to handle ajax stuff