2

So I may be asking the wrong question, so please leave comments and I'll adjust. I was told by another developer that when using redux, I should do ALL API calls within actions and create reducers for them. But I feel that sometimes making the call directly in the component will save me a TON of code. Are there best practices for this sort of thing?

Community
  • 1
  • 1
Shamoon
  • 41,293
  • 91
  • 306
  • 570
  • You are supposed to use Redux as centralised state management. You could have a list of tasks and a detailed view as components with independent states, and could enter a state where "task x completed" in the detailed view and "task x in progress" in the list. Some trivial actions, like fetching data for autocomplete can happen outside the state store. – Jesvin Jose Feb 22 '17 at 16:46
  • 1
    I'd like to add that it's also much easier to extend the functionality if things are outside of components. for example if you'd like to show a spinner in the entire app while your component is loading, that would be very ugly to do from inside a component. lots of refactoring would be done just to enable what would otherwise be a simple change – Patrick Feb 22 '17 at 16:55

2 Answers2

5

If the data you are getting from the API is only going to be consumed by a single component then you are fine to write it as part of your component (or better still, a container component). I believe the rationale behind doing your API calls in actions is to ensure that the single source of truth is maintained (the main reason to use 'the react/redux way' for me personally). If you are bringing in data from your API that is to be consumed by multiple components then use redux to ensure the same state is maintained by redux and passed to all components that use it.

Anthony Cregan
  • 960
  • 11
  • 25
2

This was previously answered by Redux's creator, Dan Abramov, here: Why do we need middleware for async flow in Redux? .

The summary:

It’s just inconvenient in a large application because you’ll have different components performing the same actions, you might want to debounce some actions, or keep some local state like auto-incrementing IDs close to action creators, etc. So it is just easier from the maintenance point of view to extract action creators into separate functions.

Community
  • 1
  • 1
markerikson
  • 63,178
  • 10
  • 141
  • 157