0

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.

3
  • Could you log the response? Commented May 23, 2019 at 15:00
  • @Claim0013 I Updated the question , please take a look at . Could you help me please ? Commented May 23, 2019 at 15:16
  • 1
    You are destructuring this.state incorrectly. It should be const {locations} = this.state; Commented May 23, 2019 at 19:50

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

Comments

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.