1

I am trying to fetch posts from wordpress RESTapi-v2 in react component.The api supplies data in json format.But fetch response in Reactjs is returning null array of posts

below is the code

class Posts extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      posts: ''
    }
    this.fetchposts = this.fetchposts.bind(this);

  }
  fetchposts(){
    fetch("http://smashingdevs.com/wp-json/wp/v2/posts/")
      .then( 
            (result)=> {
              this.setState({
                isLoaded: true,
                posts: result,
              });
            }
         );
      console.log(this.state.posts);

  }
  render() {
    return (
      <div>
        <h2>Hello  there</h2>
        <button onClick={this.fetchposts}>
          fetch posts
        </button>
      </div>
    );
  }
}

this request requires no authentication you can check it form http://smashingdevs.com/wp-json/wp/v2/posts/.

How can i debug this? is there anyway to see what posts are being fetched in console?

1
  • your console is at wrong place Commented Aug 2, 2018 at 14:57

2 Answers 2

4

a fetch call returns a response object. If you need json you must first parse it.

fetch('http://example.com/movies.json')
    .then((response) => {
        return response.json();
    })
    .then((myJson) => {
        this.setState({
          isLoaded: true,
          posts: myJson,
        });
        console.log(myJson);
    });

If you have async/await support in your app you can actually write it in a nicer way

async fetchposts() {
  let response = await fetch('http://example.com/movies.json');
  let json = await response.json();

  // do whatever
}

Another piece of advise: wrap your fetch call in a try catch and check for any errors that might occurr.

Sign up to request clarification or add additional context in comments.

Comments

1

The fetch api specifies that you need to transform the response into JSON before accessing the data.

Using Fetch Documentation

Example:

fetch('http://example.com/movies.json')
    .then((response) => {
        return response.json();
    })
    .then((myJson) => {
        console.log(myJson);
    });

Here we are fetching a JSON file across the network and print it to the console. The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and returns a promise containing the response (a Response object).

This is just an HTTP response of course, not the actual JSON. To extract the JSON body content from the response, we use the json() method (defined on the Body mixin, which is implemented by both the Request and Response objects.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.