Ad

Where To Put Network Calls In A React+redux App

- 1 answer

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?

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad