Answer the question
In order to leave comments, you need to log in
How to properly use mapStateToProps with asynchronous component behavior?
There is a component that receives information from the server. If the information has not been loaded, the load function is called in the componentDidMount() hook. mapStateToProps naturally does not wait for the download to finish and returns an empty object. Currently I have written the following code:
class CoinDetails extends React.Component {
componentDidMount(){
if (this.props.isLoading){
this.props.fetchCoinData() //старт загрузки, если данных нет
};
}
render(){
if (this.props.isLoading){
return (
<div>
'Loading ...'
</div>
)
} else {
return (
<div>
{this.props.coin.name}
</div>
)
}
}
}
const coinSelector = (state, ownProps) =>
state.coins.data.find(coin => coin.symbol === ownProps.match.params.id);
const mapStateToProps = (state, ownProps) => {
if (state.coins.hasOwnProperty('data')){ //если данные есть
return {
coin: coinSelector(state, ownProps),
isLoading: state.isLoading.coins,
}
} else { //данных нет
return {
isLoading: state.isLoading.coins
}
}
};
const mapDispatchToProps = {
fetchCoinData,
}
export default connect(mapStateToProps, mapDispatchToProps)(CoinDetails);
Answer the question
In order to leave comments, you need to log in
Don't handle stuff like this in mapStateToProps. Leave it simple:
const mapStateToProps = (state, ownProps) => ({
coin: coinSelector(state, ownProps),
isLoading: isCoinsLoadingSelector(state),
});
render() {
const { coin, isLoading } = this.props;
if (isLoading) return <Preloader />;
if (!isLoading && !coin) return <NotFound />;
return <CoinDetails coin={coin} />;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question