Skip to content

Instantly share code, notes, and snippets.

@stevensacks
Last active July 5, 2019 11:56
Show Gist options
  • Save stevensacks/8d78b0feda2e9f9aa1fe73c87e13ed1b to your computer and use it in GitHub Desktop.
Save stevensacks/8d78b0feda2e9f9aa1fe73c87e13ed1b to your computer and use it in GitHub Desktop.

Revisions

  1. stevensacks revised this gist Jul 5, 2019. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion redux-axios.js
    Original file line number Diff line number Diff line change
    @@ -5,7 +5,7 @@ export default store => next => action => {
    const {dispatch} = store;
    if (action.payload && action.payload.axios) {
    return new Promise((res, rej) => {
    const apiToken = store.getState().getIn(['auth', 'token']);
    const apiToken = store.getState().apiToken;
    const payload = {
    ...action.payload.axios,
    headers: {
  2. stevensacks renamed this gist Aug 1, 2018. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. stevensacks created this gist Aug 1, 2018.
    50 changes: 50 additions & 0 deletions redux-axios
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    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().getIn(['auth', 'token']);
    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);
    };