Last active
May 4, 2016 17:09
-
-
Save pdewouters/328ee880292caf2c871c6c0df50e9630 to your computer and use it in GitHub Desktop.
Redux Promise Middleware and Thunk example
This file contains hidden or 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
// 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