0

I have this empty state variable called data like this data: {} and when I receive a json object from my backend, I want the empty object to be the object I passed in through my backend. Say my json I received from my backend is this:

{
  "data": {
    "keywords": {
      "Mrs. Johnson": 87
    }, 
    "score": 67
  }
}

How do I make it so that data variable in my this.state gets updated to this:

"data": {
      "data": {
        "keywords": {
          "Mrs. Johnson": 87
        }, 
        "score": 67
      }
    }

so I can access elements like the score inside it using this.state.data.data.score?

Here is my react code:

class Test extends Component {
    constructor() {
        super()
        this.state = {
          data: {}
        }
    }

    const options = {
        method: "POST",
        headers: {
            'Content-Type': 'application/json;charset=utf-8', 
        },
        body: JSON.stringify(this.state.text) // Irrelevant
    };
    console.log("hi")
    fetch("http://127.0.0.1:5000/", options)
        .then(response=> response.text())
        .then(json => this.setState({data: json})) // This doesn't work

}
0

1 Answer 1

2

You want the response to be parsed into a json object instead of text:

fetch("http://127.0.0.1:5000/", options)
  .then(response=> response.json()) //notice the change here
  .then(json => this.setState({data: json}))
Sign up to request clarification or add additional context in comments.

2 Comments

When I changed it to json(), I tried console.log(this.state.data)ing the data after the fetch request and then statements, and the object showed up empty. Do you know why this happens and how I can fix it?
setState does not finish setting the state synchronously. You are probably running into the situation where you printed this.state.data and then setState finishes setting the state. Try printing out the state at the place you want to use it. It should update eventually.

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.