Soccerball123
Soccerball123

Reputation: 869

How can I set a a state variable to an object in react?

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

}

Upvotes: 0

Views: 608

Answers (1)

Hanchen Jiang
Hanchen Jiang

Reputation: 2682

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}))

Upvotes: 2

Related Questions