Search code examples
javascriptreactjsgettypeerroraxios

Getting empty object in axios GET request


I am pulling posts from WordPress blog site. But when I console log state posts and response in .then() I get Response as empty object [object object] and state as undefined.

Where am I going wrong?

I am also getting following error:

TypeError: Cannot read property 'map' of undefined

Code:

import React, {Component} from 'react';
import axios from 'axios';
import Post from './Post/Post';

class Blog extends Component {

    state = {
        posts: []
    }

    componentDidMount(){
        axios.get("https://public-api.wordpress.com/rest/v1.1/sites/ishhaanpatel.wordpress.com/posts")
        .then( response => {
            this.setState({posts: response.posts});
            console.log("Here are the posts: "+ this.state.posts);
            console.log("Here is the response: "+ response);

        });
    }

    render(){
         const posts = this.state.posts.map( post => {
             return <Post title={post.title} key={post.ID} author={post.author.name}  />;
         });
        return (
            <div>
                {posts}
            </div>
        );
    }
}

export default Blog;

Solution

  • You are having problem with asyncronous.

    setState is async. So, you won't immediately get the value in this.state.posts.

    To solve this problem you can use callbacks as follows:

    this.setState({ posts: response.posts }, () => {
        console.log(this.state.posts);
    });
    

    Also your posts is nested inside response.data. So, your setState should look something like:

    this.setState({ posts: response.data.posts }, () => {
        console.log(this.state.posts);
    });