2

So my scenario is like this:

  1. I have 2 types of requests: "public" requests which don't require authorization information, and "authorized" requests which do.
  2. For authorized requests, before actually sending every request I must put auth info into the header. After the request finishes, the new access token returned from the server should be saved into the state.

So a lot of my actions currently looks like this:

export const asyncAction = (id) => async (dispatch, getState) => {
  const { auth } = getState()
  const config = {
    headers: {
      "access-token": auth["access-token"],
      "client": auth.client,
      "uid": auth.uid
    }
  }
  const request = await axios.get(`${API_URL}`, config)

  dispatch({ type: UPDATE_USER_ACCESS_TOKEN, payload: request})

  dispatch({ type: ANOTHER_ACTION, payload: request.data })
}

I did some research and there are 2 possible ways to do this: Axios interceptor, or write a Redux middleware.

I feel like Axios interceptor, at least for the response part, is not the best solution here as it is intended to just do something with the response data, while I need to dispatch another action after I complete updating the new access-token, and I don't want to export the store to manually dispatch my actions, which is an anti-pattern. (as I mentioned the flow is: putting auth info into headers => send request => if it succeeds, then save the new access-token to Redux store for later use, then dispatch other actions; if it fails, do some error handlings).

Then I found this lib but I think I'm too dumb to understand the documentation:

https://github.com/svrcekmichal/redux-axios-middleware

Can someone please give me an example of how to do this? Both using that lib and writing custom middleware from scratch are fine for me. Thanks!

Thiem Nguyen
  • 6,345
  • 7
  • 30
  • 50

0 Answers0