0

Hello for some reason React would not update the state globally,

  componentDidMount() {
    var id = window.location.href.split('/')[3]
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://reactAppBackend/edit/" + id);
    xhr.send();
    xhr.onloadend = () => {
      this.setState({singlePost: JSON.parse(xhr.responseText)})
      console.log(this.state.singlePost[0])
    };
  }

when I run this the console log return data this data

{_id: "5e6016adb8c32b00883f55f5", postTitle: "RE4", postContent: "the best ", __v: 0}

but when I try to render the state:

  render() {
    return (
      <div>{this.state.singlePost[0]}</div>
    )
  }

it is not rendering anything.

Antoni
  • 1,316
  • 2
  • 16
  • 42
n2kin
  • 3
  • 3

3 Answers3

0

There's a typo inside your render. It's should be singlePost


render() {
    return (
      <div>{this.state.singlePost[0]}</div>
    )
  }
joy08
  • 9,004
  • 8
  • 38
  • 73
0

You have a typo here: <div>{this.state.siglePost[0]}</div>

siglePost, should be singlePost

Sebastian Berglönn
  • 3,920
  • 2
  • 17
  • 33
0

The state was an array, I have managed to show the response with the map function.

  render() {
    return (
      <div>
        {this.state.singlePost.map(post => {
          return (
            <div>
              <p>{post.postTitle}</p>
              <p>{post.postContent}</p>
              <img src={post.postPicturePath} />
            </div>
          );
        })}
      </div>
    );
  }
n2kin
  • 3
  • 3