I am working a project which use react-redux and redux-thunk for development. Previously the approach was to check api calls one by one and manually check if all the data is being fetched. As I found that after v7.0, batch
is introduced in react-redux
to help solving the issue. But the page also requires loading indicator as well.
The current approach is having several dispatches in batch to reduce unnecessary re-rendering, and manually check if all the data is fetched in the render, but I was wondering if there is any other method that can be applied on the batch
to cut some hard code check.
Here is the current sample code:
// in action file
...
function fetchSomeData() {
// call api to store data
return dispatch => {
batch(() => {
dispatch(fetchData1());
dispatch(fetchData2());
dispatch(fetchData3());
..some more dispatches...
});
}
}
...
// in react component
dataLoaded(){
....retrieve all the data from different places...
if (!data1) return false;
if (!data2) return false;
...check all the data...
return true;
}
...
render() {
if (this.dataLoaded()) {
return actual_content;
} else {
return loading_content;
}
}
...
I tried to directly use then
, and create another method, return batch
, call fetchSomeData
, then use then()
, but all produce "Cannot read property 'then' of undefined" error.
I also used Promise.all
, but with no luck. Use of Promise.all
is shown as below:
function fetchSomeData() {
// call api to store data
return dispatch => {
Promise.all([
dispatch(fetchData1());
dispatch(fetchData2());
dispatch(fetchData3());
..some more dispatches...
])
.then(() => dispatch(setLoading(false)));
}
}
I also checked other posts on the stackoverflow, but many posts suggest other middleware, and additional dependency requires approval as one of the requirement is limited bandwidth, use minimal dependencies as needed.