I'm trying to get some thoughts on what people would consider the best practices for how people organize network calls in their react+redux apps. I usually let my components make the calls, get data and then pass that into an action that will get reduced. Is this the best practice or is it better to separate networking out of my components and place that logic somewhere else in the app, maybe in the reducers?
Redux doesn't have a Dispatcher or support many stores. Instead, there is just a single store with a single root reducing function. As your app grows, instead of adding stores, you split the root reducer into smaller reducers independently operating on the different parts of the state tree.
The connect() function connects a React component to a Redux store. It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.
The best place to make network calls is in your action creators. However, you're going to need some middleware to make that work best. Take a look at this promise-middleware (in fact, I'd suggest checking out that whole tutorial). If you use that middleware, you can have action creators that return a promise and also have three action types - one for the request, one to handle successful responses, and one to handle failed requests. Then you just listen for those 3 actions in your reducers.
So with that middleware, you could have an action creator like this:
function networkCall() {
return {
types: ['MAKE_REQUEST', 'REQUEST_SUCCESS', 'REQUEST_FAILURE'],
promise: () => {
return new Promise((resolve, reject) => {
$.ajax({
url: 'example.com/api'
type: 'GET'
});
})
}
}
}
Obviously you are free to build your own promise middleware, but that should set you in the right direction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With