1

I have a situation that I need to send two params in my post requests using axios to all my endpoints. These parameters are already in my store.

So, I create a "middleware" to procede all my requests like so:

const POST = async (url, body = {}) => {
  const {Token, UserId} = store.getState().User
  const {DeviceIdentifier} = await GetDeviceInfo()
  const data = {AgentId: UserId, DeviceId: DeviceIdentifier, ...body}
  const response = await axios.post(`${BASE_URL}${url}$`, data, {
    headers: {Authorization: `Bearer ${Token}`},
  })

  if (!response.data.Logged) {
    logoutUser()
    return false
  }

  return response
}

But, I've been reading a lot of articles saying that using getState() like that is not a good idea...

What should be the best aproch in a situation like that?

Thank you so much!

Rangel Netto
  • 11
  • 1
  • 1
  • 1
    Dan Abramov passes a `getState` argument in his Redux Thunk library (`return (dispatch, getState) => {...}`). See [his answer](https://stackoverflow.com/a/34599594/327074) to a related question. So it seems like it's reasonable to be able to use `getState` in middleware. – icc97 Oct 30 '18 at 18:11
  • Is this middleware an action creator – Shubham Khatri Oct 30 '18 at 18:12
  • Sure... Thank you guys! – Rangel Netto Oct 30 '18 at 19:12

2 Answers2

1

When using redux thunk you can supply two arguments dispatch and getState. To supply more arguments:

const store = createStore(
  reducer,
  applyMiddleware(thunk.withExtraArgument({ url, body }))
)

// .withExtraArgument(url) // to supply further one arguments only

And then you can use getState like:

const POST = async (dispatch, getState, {url, body = {}}) => {
  ...
  getState().User
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0

Using getState() in a middleware is totally fine - that's why it's there!

If you'd like to read some extended discussion of some hypothetical concerns and my reasons why it's still okay, my post Idiomatic Redux: Thoughts on Thunks, Sagas, Abstraction, and Reusability goes into further details.

markerikson
  • 63,178
  • 10
  • 141
  • 157