Reputation: 243
I've looked into consuming APIs in Redux using the redux-thunk middleware. I understand the flow of calling an API from Redux, and I understand how to structure a slice of my state to reflect the status of an API call, i.e. fetching, success, or fail. What I'd like to know now is: how do I structure a very large application to avoid boilerplate code? From what I gathered reading the docs, a single API call requires:
API_CALL_FETCHING
action and an API_CALL_SUCCESS
action or an API_CALL_FAIL
actionAssuming I have a resource that allows basic CRUD operations on it, naively that means I should write 12 different actions (4 crud operations * 3 API status actions per call). Now imagine I have many resources that allow CRUD operations, and this starts to get huge.
Is there any eloquent way to condense the code necessary to make many API calls? Or does having a large application simply demand lots of repetition in this area?
Thanks!
Upvotes: 0
Views: 740
Reputation: 67627
Yes. There's numerous ways to abstract the process of making API calls, and dozens of existing libraries to help with that.
Generically speaking, you can write "factory functions" that take some set of parameters (API endpoints, data descriptions, etc), and return a set of actions, reducers, and other logic for actually making the API calls and handling the data.
For existing examples, see the Action/Reducer Generators#Network Requests and Entity/Collection Management sections of my Redux addons catalog. There's also some more intentional abstraction layers on top of Redux, like redux-tiles and Kea.
Upvotes: 1