js_248
js_248

Reputation: 2112

React state data null for the first time

I am taking 'data' from the api.For the first time when component render it is getting data as null but after some time it is having api data.I am getting data from api but not able to render it due to initial null value.

class CallData extends Component {
      componentWillMount() {
        if (this.props.onPageLoad) {
          this.props.onPageLoad();
        }
      }


      render() {
        const {data} = this.props;
        console.log("data of table...");
        console.log({data});
        if (!data.length) {
          return null;
        }

        return(
          <div>
            {console.log(data)};

          </div>
        );

      }
    }


    export default CallData;

Upvotes: 1

Views: 2710

Answers (1)

radix
radix

Reputation: 760

I think you have two good options:

  1. Sepcify default props for the component https://facebook.github.io/react/docs/typechecking-with-proptypes.html#default-prop-values

  2. In render method declare a default value for the data: const {data = {}} = this.props;

3.

return(
      {this.props.data && <div>
        {console.log(data)};
      </div>}
    )

Upvotes: 3

Related Questions