Skip to content

Instantly share code, notes, and snippets.

@Porter97
Created March 30, 2020 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Porter97/5ebfa320524eb21df189e9ce0b9175e6 to your computer and use it in GitHub Desktop.
Save Porter97/5ebfa320524eb21df189e9ce0b9175e6 to your computer and use it in GitHub Desktop.
const promiseMiddleware = store => next => action => {
if (isPromise(action.payload)) {
store.dispatch({type: 'ASYNC_START', subtype: action.type});
action.payload.then(
res => {
action.payload = res;
store.dispatch(action);
},
error => {
action.error = true;
action.payload = error.response.body;
store.dispatch(action);
}
);
return;
}
next(action);
};
function isPromise(v) {
return v && typeof v.then === 'function';
}
const localStorageMiddleware = store => next => action => {
if (action.type === 'REGISTER' || action.type === 'LOGIN') {
if (!action.error) {
window.localStorage.setItem('currentUser', action.payload.user);
store.redirectTo = '/'
}
} else if (action.type === 'LOGOUT') {
window.localStorage.setItem('currentUser', '');
}
next(action);
};
export {
localStorageMiddleware,
promiseMiddleware
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment