0
votes

Here is the component code. it is wrapped in connect function with mapStateToProps and mapDispatchToProps set appropriately.

   //Parent component
    componentDidMount() 
    {this.props.dispatchAction()}//dispatches action which sets requestPending state in redux to true and fetches data. when the data is fetched it sets requestPending to false again.

then in render method of parent component.

if (this.props.requestPending) return <Loading />; 
if (!this.props.requestPending) return <SecondChild {...this.props.data} />; 

the problem is that when parent component mounts, for split second requestPending is false so it renders SecondChild component. which gives undefined error since this.props.data is not fetched yet.

What is the appropriate way to render this JSX ?

2
You should provide more from your code.Chanuka Sandeepa

2 Answers

0
votes

you can use terinary operator.

return (

   this.props.requestPending ? <Loading /> : <SecondChild {...this.props.data} />
)
0
votes

Initial data value could be set to null and

render() {
  const { requestPending, data } = props;

  if(requestPending || !data) {
    return  <Loading />;
  }

  return  <SecondChild {...this.props.data} />;
}

Though I would recommend having an error state and showing an error page incase there is an api error and data doesn't load at all. Showing an infinite loader is bad UX.