Skip to content

Instantly share code, notes, and snippets.

@whichsteveyp
Last active October 25, 2017 22:53
Show Gist options
  • Save whichsteveyp/e6bb2a88d7afa5ad6d4e2cb4d9c4692b to your computer and use it in GitHub Desktop.
Save whichsteveyp/e6bb2a88d7afa5ad6d4e2cb4d9c4692b to your computer and use it in GitHub Desktop.
Dispatch Helpers API (allowing for custom XHR (or anything app controlled behavior
/*
Currently, I use `readResources(...)` for two main reasons:
1. easy conformity from my API responses into the reducers in a "resourceful" way,
along with all the great `getStatus()` and `meta` and `lists` benefits that each
slice has
2. it also makes XHRs for me and updates the above automatically for me
An issue with this is any time I need to control my _own_ XHRs, I loose out on the
convenience of both #1 _and_ #2 above. This is because now I need to 'memorize' or
understand the `dispatch(...)` pattern that resourceful reducers can interpret.
Another issue with this is that I'm locked into the underlying `xhr` library, and
cannot use (for example) superagent, or perhaps another transport like WebSockets
What if we could help make `dispatch(...)` calls easier for folks to allow for this
control and flexibility?
*/
import {createActions, CrudTypes} from 'redux-resource-actions';
const readActions = createActions({
resourceName: 'books',
crudType: CrudTypes.READ,
});
const readBooksReset = () => dispatch => {
dispatch(readActions.null());
};
export readBooksReset;
const readBooks = options => dispatch => {
dispatch(readActions.pending());
return fetch('/my/resources')
.then(res => {
dispatch({
...options,
...readActions.succeeded(res),
})
})
.catch(err => dispatch(readActions.failed(err)))
}
export readBooks
// this is just an aggregate of the types of `redux-thunk#dispatch()` calls that
// `resourceful-action-creators#performXhr()` makes for you while perfomring XHRs
// we are mapping them to the `resourceful-redux#getStatus()` key associated with each
// .pending
dispatch({
...options,
type: actionTypes[`${crudType}_RESOURCES_PENDING`],
// This may seem strange, but any unresolved request has a status code of 0
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status
statusCode: 0
});
// .null
dispatch({
...options,
type: actionTypes[`${crudType}_RESOURCES_NULL`],
statusCode,
res
});
// .failed
dispatch({
...options,
type: actionTypes[`${crudType}_RESOURCES_FAILED`],
statusCode,
res,
err,
});
// .succeeded
dispatch({
...options,
type: actionTypes[`${crudType}_RESOURCES_SUCCEEDED`],
statusCode,
resources,
res
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment