Maryam Ghafarinia
Maryam Ghafarinia

Reputation: 458

fetch data in react returns {}

I have a react component , and I want to fill its state by fetching data from the url that I tested in browser and returns json data . but in my code I got nothing, here is my code :

    fetch(`https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/posts.json`)
      .then(response => response.json())
    //.then(data => JSON.stringify(data))
      .then(data => this.setState({
      latitude: position.coords.latitude, // this ois ok 
      longitude: position.coords.longitude, /// this is ok 
      locations : data // here I get {}
    }));

Problem is here in my render function

const { location } = this.state.locations;
alert("1" +JSON.stringify( this.state.locations));
alert("2" + JSON.stringify( location));

First alert is full with correct data but second alert returns undefined.

Upvotes: 0

Views: 37

Answers (1)

Will Jenkins
Will Jenkins

Reputation: 9787

It looks like you're trying to destructure location from this reponse:

{
  "posts": [
    {
      "_id": "5b3f761e21d434001487ad99",
      "title": "Hello Word!",
      "content": "The world is green!",
      "__v": 0
    },
    {
      "_id": "5b3f76b521d434001487ad9a",
      "title": "Sed porttitor lectus nibh",
      "content": "Sed porttitor lectus nibh. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Pellentesque in ipsum id orci porta dapibus. Proin eget tortor risus. Pellentesque in ipsum id orci porta dapibus. Curabitur aliquet quam id dui posuere blandit. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Pellentesque in ipsum id orci porta dapibus. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui.",
      "__v": 0
    }
  ]
}

As you can see, it doesn't have a location property so the result of your destructure will be undefined. Are you hitting the right endpoint?

Upvotes: 1

Related Questions