Skip to content

Instantly share code, notes, and snippets.

@pdewouters
Last active May 4, 2016 17:09
Show Gist options
  • Save pdewouters/328ee880292caf2c871c6c0df50e9630 to your computer and use it in GitHub Desktop.
Save pdewouters/328ee880292caf2c871c6c0df50e9630 to your computer and use it in GitHub Desktop.
Redux Promise Middleware and Thunk example
// actions.js
// Gets list of venues for a city from Foursquare API, then fetches all attendees for those venues from an express server API with mongoDB backend
export const fetchVenues = (city) => {
return (dispatch, getState) => {
return dispatch({
type: FETCH_VENUES,
payload: {
promise: getVenues(city)
}
}).then(
response => {
const venueIds = response.value.data.response.groups[0].items.map((item) => {
return item.venue.id
})
dispatch(fetchVenueAttendees(venueIds))
}
)
}
}
export const fetchVenueAttendees = (venueIds) => {
return {
type: FETCH_VENUES_ATTENDEES, payload: { promise: getVenuesAttendees(venueIds) }
}
}
//reducer.js
import { FETCH_VENUES_ATTENDEES } from '../actions/types'
export default function(state = {
isFulfilled: false,
items: []
}, action) {
switch(action.type) {
case `${FETCH_VENUES_ATTENDEES}_PENDING`:
return Object.assign({}, state, {
isFulfilled: false
})
case `${FETCH_VENUES_ATTENDEES}_FULFILLED`:
return Object.assign({}, state, {
isFulfilled: true,
items: action.payload.data,
lastUpdated: action.receivedAt
})
}
return state
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment