0

I am trying to do a basic thing with react, which is access an endpoint created by my locally installed WordPress website so that I can use that data and render it in a way I like.

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export default class Widget extends Component {
  constructor(props) {
    super(props);

    var data = fetch("http://localhost:8888/test-site/wp-json/wp/v2/posts")
      .then(data => data.json())
      .then(data => {
        console.log(data);


        // this.state = {
        //   value: 'foo2',
        //   posts: data.value,
        // };

      })


    this.state = {
      value: 'foo2',
      posts: data.value,
    };

  }


  render() {
    return (
      <div>
        <p>value: {this.state.posts}</p>
      </div>
    );
  }
}

Widget.propTypes = {
  wpObject: PropTypes.object
};

I am trying to set the state to the data but it is returned as a promise. Apparently I can console.log the data but I cannot use it in the render function. You can see that I try to set the state in the second .then() but when I uncomment that and delete the thing below it everything stops working. If I cannot set the state inside the .then() how do I use the returned data in the render() function?

2
  • This is really more of a React/JavaScript question. The fact that the URL is a WordPress endpoint isn't really relevant. As such it would be more appropriate at stackoverflow.com. Commented Jul 4, 2019 at 13:11
  • oh, my mistake... that is exactly why I thought the question belonged here
    – brothman01
    Commented Jul 4, 2019 at 14:32

0

Your Answer

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

Browse other questions tagged or ask your own question.