Deciding which redux container to call the API

Redux container components

In the component tree example, Component C and E require the same data. This data is retrieved from an API call that is triggered by dispatching an action.

My question is , where should this send operation take place?

This can happen in the method componentWillMount()

(via mapDispatchToProps()

) of the first reciprocal parent, component B in this case. The problem is that component B now has a deep knowledge of the data it needs for children and I can no longer reuse component C or E without some higher order component.

Alternatively this can happen in componentWillMount()

(again, through mapDispatchToProps()

) both C and E components, potentially using debounce to create an action (helper libraries available). My concern with this is that now the C and E components have some knowledge that they exist on the same page as they do in others, otherwise they won't give up. Even worse, if Component C appears on another page without Component E, it doesn't necessarily take away the action.

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

+3


source to share


1 answer


One approach would be to have both components call the same thunk action creator, which should check if the request is actually required. 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 keep track of "we're getting now"? value in your state, and also have logic to figure out if the data has already been loaded. This way you can call the thunk multiple times and only actually get it once.

+2


source







All Articles