I can\'t do map() function for rendering because the length of the array is always 0, even though I get data from the array. Is there a way to set time interval until the asynch
First off, make sure the function call that initiates data fetching is invoked after the component is mounted. You do this so that when the state changes a re-render may occur. Secondly, before mapping through the array you expect to have data, make sure that it has something. That is, instead of
{ someArray.map() }
rather do
{ someArray.length > 0 && someArray.map() }
You probably don't need to do this, but it's good practice.
Thirdly, to properly wait for the results to be found, the usual practice is using redux-thunk. Redux-thunk helps in delaying dispatching an action until some criteria is met (in your case, you want to dispatch a "data found" action only when the data has been found).
Here is an example where we fetch carousel pictures and map through them in the view component. You can easily adapt this to your project.
export function loadCarouselSlidesThunk() {
return dispatch => {
dispatch(setIsLoadingAction(true));
getCarouselSlides().then(pictures =>
dispatch(setCarouselSlidesAction(pictures)));
};
}
From here, your reducer can simply populate the part of state that cares about the slides, like so
export default function carouselReducer(state = initialSate, action) {
switch (action.type) {
case setIsLoading.actionType:
return { ...state, isLoading: action.payload };
case setCarouselSlides.actionType:
return { ...state, carouselSlides: action.payload, isLoading: false };
default:
return state;
}
}
As soon as the state is updated, your whole app re-renders and now you will be able to map through the actual data.
So, the best way, in my opinion, is to use redux-thunk along with promises. Refer to the link above on how to set up redux in your application. If not familiar with promises, please refer to this.
Cheers