Skip to content

Instantly share code, notes, and snippets.

@nickav
Last active October 18, 2017 14:56
Show Gist options
  • Save nickav/12fe37d51712e02daa1c6f2e0e175b2b to your computer and use it in GitHub Desktop.
Save nickav/12fe37d51712e02daa1c6f2e0e175b2b to your computer and use it in GitHub Desktop.
Redux Async Wrappers
/**
* Redux async helpers.
*/
// Constants
const REQUEST = 'request';
const SUCCESS = 'succces';
const FAILURE = 'failure';
/** Request status can only be one of these: */
export const status = { REQUEST, SUCCESS, FAILURE };
/**
* Wraps the promise returning a Thunk Action which will dispatch the
* request status lifecycle actions.
*/
export const request = (type, promise, meta = {}) => dispatch => {
dispatch({ type, status: REQUEST, meta });
return promise
.then(response => {
dispatch({
type,
status: SUCCESS,
response,
data: response.data || response,
meta
});
return response;
})
.catch(error => {
dispatch({ type, status: FAILURE, error, meta });
console.error(error);
throw error;
});
};
/**
* Counterpart to request wrapper. Sets up a reducer that will have loading,
* data and error keys.
*/
const initialState = { loading: false, data: null, error: null };
export const reducer = type => (state = initialState, action) => ({
loading: action.type === type ? action.status === REQUEST : state.loading,
data: action.type === type ? action.data || state.data : state.data,
error: action.type === type ? action.error || null : state.error
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment