svrcekmichal / redux-axios-middleware

Redux middleware for fetching data with axios HTTP client
MIT License
922 stars 96 forks source link

is there a way to set authorization header using this globally? #95

Closed videni closed 5 years ago

videni commented 5 years ago

because the user token is saved in AsyncStorage, a request can make only after the token is retrieved from AsyncStorage, right now I pass a header parameters to every action, this is very tedious.

export function load(headers = {}) {
  return {
    type: LOAD,
    payload: {
      request: {
        url: '/api/admin/profile',
        headers: {
          Accept: 'application/json',
          ...headers,
        },
      },
      options: {
        returnRejectedPromiseOnError: true,
      },
    },
  };
}

as you know it doesn't work when set authorization header in the middleware config

const middlewareConfig = {
  interceptors: {
    request: [
      function ({ getState, dispatch, getSourceAction }, config) {
          AsyncStorage.getItem("userToken").then((value) => {
              config.headers.Authorization = `Bearer ${value}`;
          })
          return config;
      },
    ],
  },
};

how-to-send-axios-authorization-header-in-reactnative

ajanauskas commented 5 years ago

Why don't you store token redux state? Then you could fetch token using getState during request interception. You could also use redux-persist to persist token store part with AsyncStorage. This I believe is much more performant than calling AsyncStorage on each request since you don't need constantly communicate with native via bridge.

videni commented 5 years ago

@ajanauskas , I see , thanks a lot

tamangsuresh commented 3 years ago

@ajanauskas i did try to do as you said. But things aren't working. App will not rehydrate. Have you found any solution on it.