Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios response interceptor with combination with redux reducer

   import React from "react";
    import axios from "axios";
    import {push} from "react-router-redux";
    import {actionTypes} from "../Patient/actions";
    import {put, call} from "redux-saga/effects";
    import {updatePermissionsAction} from "../Patient/actions"

    // Add a response interceptor for getting permissions
    axios.interceptors.response.use(function(response) {

        console.log("in interceptorXXXXXXXXXXX");
        if(response.headers.permissions == null) {
            return response;
        }
        var permissions = response.headers.permissions.split(',');

        permissions.forEach((permission, index, permissionArray) => {
            permissionArray[index] = permission.trim();
        });


        put({
             type: actionTypes.UPDATE_PERMISSIONS,
             permissions: permissions
         });
        return response;
    }, function (error) {
        // Do something with response error

    });

The interceptor is being called, but the put has no effect. When my sagas call the reducer that work fine.

Maybe the interceptor can't use this pattern? Is there a way from the interceptor to call the reducer?

like image 366
Benno Avatar asked Nov 09 '22 03:11

Benno


1 Answers

Maybe the saga may need to be exported and added to redux with applyMiddleware to be able to use "put" to dispatch actions(?). Not totally sure how it would be implemented in this case.

I was in a similar situation and I could dispatch an action by importing the store, then call the action with store.dispatch(myaction(data)); (I didn't use saga).

import {myAction} from 'actionCreators';
import store from 'store';

axios.interceptors.response.use(response => {

    if('dataProperty' in response.data){

        store.dispatch(myAction(response.data.dataProperty));

    }
    return response;

}
like image 61
Galivan Avatar answered Dec 19 '22 13:12

Galivan