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 asynchronous array is loaded properly?
This is mine code:
function ShortcutComponent({ usershortcuts }) {
console.log(usershortcuts); // I get an array
console.log(usershortcuts.length); //I get 0
return (
<Button ui="headerButton" arrow={false} ripple={false} iconCls="icon-directions" border={false} handler={() => this.loadData()}>
<Menu title="Shortcuts">
{usershortcuts.map((item) => {
<MenuItem key={item.id} iconCls={item.shortcutDefinition.iconCls} text={item.shortcutDefinition.description} />
}
</Menu>
</Button>
)
}
const mapStateToProps = (state) => {
return {
usershortcuts: state.usershortcuts
}
};
const mapDispatchToProps = (dispatch) => {
return {
actions: bindActionCreators(usershortcutAction, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps) (ShortcutComponent);
As a evidence here is the picture:
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
rather do
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.
From here, your reducer can simply populate the part of state that cares about the slides, like so
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