简体   繁体   中英

How to render data in react getting undefined state?

I am fetching data inside componentDidMount but i get undefined during initial render and again render happens and during that time the state variable gets populated. Now when it is not undefined and after population I want to destructure it and display the data inside my component.

Note: getProjectDetails() makes a GET req to populate the data.

I am getting typer error name of undefined.

  constructor(props) {
            super(props);
            this.state = {
               projectDetails: ''
            };
        }

    componentDidMount() {
            getProjectDetails(this.props.logged_in_user, this.props.projectId)
                .then( res => {
                    this.setState({projectDetails: res});
                })
                .catch(err => {
                    console.log('Error: ' + err);
                })
        }

    //Inside render()

    render() {
            console.log('Project details from API endpoint: ', this.state.projectDetails.project)

            const { projectDetails } = this.state;
            console.log('Destructure: ', projectDetails);

            const project = this.state.projectDetails.project;

    let {  
                name,
                location,
                city,
                builder_name } = project;

You could check with the following if the state is set:

render() {
    if(this.state.projectDetails === ''){
        return <div>Loading</div>;
    }
    else{
        return <div>{this.state.projectDetails.project}</div>
    }
}

So as long as the state is false, Loading will be returned, if there is a value, then this.state.projectDetails.project gets returned. I hope that helps.

Edit: The render method will be called twice, before the data is fetched and then, after the state is set. So this would only return the data, if its really set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM