1

As seen in this answer, passing state to an ActionCreator is considered an anti-pattern. So is accessing the state with Redux Thunk Middleware. I'm wondering how to solve the following (popular) scenario:

I'm fetching items from a server, based on filters from a search form on the frontend. Naturally, I need to pass the filters to my server, so I'm doing this in my action creator

export function getResults(filters){
   return Axios.get('localhost:80/getresults/',{params:filters}).then(
      // do something with results here.
   )
}

But this is considered an anti-pattern because filters is coming from the store.

Alternatively, I could use redux thunk like this:

export function getResults(){
   return function(dispatch,getState){
      var filters = getState().reducer.filters;
      return Axios.get('localhost:80/getresults/',{params:filters}).then(
         // do something with results here.
      )
   }
}

This is also considered an anti-pattern because I'm accessing state.

So how would I implement it the correct way? Should I do the ajax call somewhere else entirely?

Community
  • 1
  • 1
PoeHaH
  • 1,936
  • 3
  • 28
  • 52
  • State shouldn't be accessed directly from action creator is the main idea in the answer you've pointed to (your second approach). But you free to pass any argument (part of the state or other object) to your action creator which is the first approach you've shown. – Ziumin Dec 09 '16 at 08:36
  • @Ziumin the answer states "Passing data such as state.something.items in an action creator is definitely an anti-pattern and is discouraged because it obscured the change history". Do they mean it's okay to pass data TO an action, just not pass it from within the action to something else? – PoeHaH Dec 09 '16 at 08:42
  • Passing state as an argument TO an action makes your action independent from the state, it even doesn't know that the state exists. And you can test it easily passing some mocked filters. But if you get the state from within your action creator becomes stateful. It's like the `add(2)` and the `add(2, 2)`. Which one is easier to test? And which one's result you can easily predict? – Ziumin Dec 09 '16 at 09:03
  • @Ziumin fair enough! thanks! – PoeHaH Dec 09 '16 at 09:08

1 Answers1

0

As much as I respect Dan, I disagree with his comment there. To me, accessing state in thunks is absolutely a useful tool, whether it be deciding whether or not to actually dispatch an action, or using the existing state to help generate the content of an action.

I would say your thunk example is perfectly acceptable.

markerikson
  • 63,178
  • 10
  • 141
  • 157