Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put network calls in a react+redux app

Tags:

reactjs

redux

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?

like image 559
shirajg Avatar asked Jan 15 '16 02:01

shirajg


People also ask

Does Redux have a dispatcher?

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.

Can I connect functional component to Redux?

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.


1 Answers

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.

like image 53
Andy Noelker Avatar answered Oct 21 '22 03:10

Andy Noelker