2
votes

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;
1
You might try to set the Async function call in a componentWillMount method, that might be better. - Eliâ Melfior
I used componentWillMount but still getting same error - fun joker
Your initial state does not have the object project. - Eliâ Melfior

1 Answers

4
votes

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.