Skip to content

Instantly share code, notes, and snippets.

@josefdlange
Created September 21, 2016 21:04
Show Gist options
  • Select an option

  • Save josefdlange/dd68023971e817432976d15ed1e89261 to your computer and use it in GitHub Desktop.

Select an option

Save josefdlange/dd68023971e817432976d15ed1e89261 to your computer and use it in GitHub Desktop.
Redux REST Example
// Actions
var startLoadingX = function() {
return {
type: START_LOADING_X // Define this above as you do with Actions.
}
}
var completeLoadingX = function(response, error) {
return {
type: COMPLETE_LOADING_X, // Ditto.
response,
error
}
}
var fetchX = function(possibleParameters) {
return dispatch => {
dispatch(startLoadingX())
myApiClientIWroteThatReturnsPromisesForApiCalls.getStuff(possibleParameters)
.then(response => dispatch(completeLoadingX(response, null)))
.catch(error => dispatch(completeLoadingX(null, error)))
}
}
// Reducer
const initialState = {
isLoadingX: false,
X: {}, // or [] I suppose, depending on the shape you're expecting your response to have!
errorLoadingX: false,
XErrorData: null
}
export default function myStoresReducer(state = initialState, action) {
switch(action.type) {
case START_LOADING_X:
return Object.assign(state, {}, {
isLoadingX: true,
errorLoadingX: false,
X: {}, // you can decide if you want to clear the actual state on every load. For the sake of UI sometimes it's nice to keep old data there to show anything but a blank component.
XErrorData: null
})
case COMPLETE_LOADING_X:
if(action.error != null) {
return Object.assign(state, {}, {
isLoadingX: false,
errorLoadingX: true,
X: {}, // Or null or you can leave it alone as discussed above.
XErrorData: action.error
})
} else {
return Object.assign(state, {}, {
isLoadingX: false,
errorLoadingX: false,
X: state.response, // If your data is embedded in a generic response data structure, this would be a good place to unwrap it, or even in the API client itself.
XErrorData: null
})
}
}
}
@josefdlange

Copy link
Copy Markdown
Author

You don't even need the first private action (of the two inside the thunk) unless you want to be keeping track of whether or not you are loading --- so that your UI can display that and/or if you want/need to do some cleanup before receiving a potential response.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment