L
L
lacront2018-11-20 07:05:48
React
lacront, 2018-11-20 07:05:48

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);

Is it even possible to implement such logic in the mapStateToProps function, or is there an easier way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-11-20
@lacront

Don't handle stuff like this in mapStateToProps. Leave it simple:

const mapStateToProps = (state, ownProps) => ({
  coin: coinSelector(state, ownProps),
  isLoading: isCoinsLoadingSelector(state),
});

In the render method:
render() {
  const { coin, isLoading } = this.props;

  if (isLoading) return <Preloader />;

  if (!isLoading && !coin) return <NotFound />;

  return <CoinDetails coin={coin} />;
}

Learn how to design the store, set the initial state, and write the render method so that it succeeds whether you get the required data or not.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question