Last active
July 5, 2019 11:56
-
-
Save stevensacks/8d78b0feda2e9f9aa1fe73c87e13ed1b to your computer and use it in GitHub Desktop.
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
import axios from 'axios'; | |
import {createAction} from 'redux-actions'; | |
export default store => next => action => { | |
const {dispatch} = store; | |
if (action.payload && action.payload.axios) { | |
return new Promise((res, rej) => { | |
const apiToken = store.getState().apiToken; | |
const payload = { | |
...action.payload.axios, | |
headers: { | |
...action.payload.axios.headers, | |
authorization: apiToken ? `Bearer ${apiToken}` : null, | |
}, | |
}; | |
axios(payload) | |
.then(response => { | |
const success = createAction( | |
`${action.type}_SUCCESS`, | |
axiosResponse => ({ | |
...action.payload, | |
axios: undefined, | |
axiosResponse, | |
}) | |
)(response.data); | |
if (action.payload.onSuccess) { | |
action.payload.onSuccess(response.data); | |
} | |
res(success); | |
return dispatch(success); | |
}) | |
.catch(error => { | |
const failed = createAction( | |
`${action.type}_FAILED`, | |
axiosError => ({ | |
...action.payload, | |
axios: undefined, | |
axiosError, | |
}) | |
)(error); | |
if (action.payload.onError) { | |
action.payload.onError(error); | |
} | |
rej(failed); | |
return dispatch(failed); | |
}); | |
}); | |
} | |
return next(action); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment