fun joker
fun joker

Reputation: 1727

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;

Upvotes: 2

Views: 2515

Answers (1)

Lukas Germerott
Lukas Germerott

Reputation: 361

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.

Upvotes: 4

Related Questions