0

I'm trying to fetch a json and include it in my state.

Strangely when I launch my ajax request with axios inside a componentDidMount and I console.log the state updated inside the render method it returns an empty object, then the state updated.

Don't mind the "undefined"

I just want to remove this empty object. How can I do ?

Here is the code :

 componentDidMount() {
    axios({
        method: 'get',
        baseURL: '/url',
        headers: {
            "foo": "bar",
            "key": "tata"
        },
        timeout: 3000,
        responseType: 'json'
    }).then(response => {
        const posts = response.data.blocks.map(post => {
            if (typeof post.description !== 'undefined' && typeof post.description !== '') {
                return post;
            } else {
                return;
            }
        });
        this.setState({posts});
    });
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
math1761
  • 13
  • 4

1 Answers1

1

componentDidMount is called after your render method and hence what you get in your render method initially is the initial state that you have set in the constructor. Since post is supposed to be an array, you can initialise it as an empty array in the constructor like

constructor(props) {
    super(props);
    this.state ={
      posts: []
    }
}

Once your request in componentDidMount is complete, the state post is set an the component will re-render and hence the second time you will see the correct data.

Check this answer too

Use componentWillMount or componentDidMount lifecycle functions for async request in React

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400