Alex
Alex

Reputation: 5636

Deciding which redux container to make API calls from

Redux Container Components

In the example component tree, Component C and E both require the same data. This data is fetched from an API call which is triggered via dispatching an action.

My question is, where should this dispatching of the fetch action occur?

It could occur in the componentWillMount() (via mapDispatchToProps()) method of the first mutual parent component, Component B in this case. The problem with this is that component B now has an intimate knowledge of the data it's children require and I can no longer re-use Component C or E without some higher-order component.

Alternatively it could occur in componentWillMount() (again, via mapDispatchToProps()) of both Component C and E, potentially using a debounce on the action creation (helper libs available). My concern with this is that now Component C and E have some knowledge that they exist on the same page as each other otherwise they wouldn't debounce. Worse still, if Component C appears on another page without Component E then it is unnecessarily debouncing an action.

Does anybody know of a cleaner pattern for fetching data to be used by multiple child components?

Upvotes: 3

Views: 299

Answers (1)

markerikson
markerikson

Reputation: 67459

One approach would be to have both components call the same thunk action creator, which should check to see if the request actually needs to be made. It might look something like this:

function loadSomeDataIfNeeded() {
    return (dispatch, getState) => {
        const state = getState();

        if(!dataAlreadyLoaded(state) && !currentlyFetchingData(state)) {
            dispatch(startFetchingData())

            fetchData()
                .then(response => {
                    dispatch(dataFetched(response));
                });
        }    
    }
}

So, track a "are we fetching right now?" value in your state, and also have logic to figure out if the data has already been loaded. That way, you can call the thunk multiple times and only actually have it fetch once.

Upvotes: 2

Related Questions