0

I have JSON I am getting from an API and once that data is fetched, I am using another API to get geocode values and adding that to the object.

Here is the initial object after fetching:

{ approved: 1
 body: "sample comments being made. "
 categories: (4) [{…}, {…}, {…}, {…}]
 created_at: "2020-12-18T19:38:43.000000Z"
 email: "janedoe@gmail.com"
 geocode: null
 id: 7
 image_id: "7"
 is_moderated: 1
 updated_at: "2020-12-21T20:57:04.000000Z"
 zip: "60611"
}

Then I am using this loop to use each object's zip to get Geocoding info and add it to each object.

for (const property in data) {
  getLocationInformation(data[property]);
  const allApprovedComments = createCommentElement(data[property]);
  commentContentParent.append(allApprovedComments);
}

This is what the getLocationInformation function looks like:

  function getLocationInformation(comment) {
    const fullPath = geoCode + '?address=' + comment.zip + '&key=' + geocodeApi;

    fetch(fullPath)
      .then(function fetchResponse(response) {
        return response.json();
      })
      .then(function parseData(data) {
        comment.geocode = {
          county: data.results[0].address_components[2].long_name,
          state: data.results[0].address_components[3].long_name,
          stateAbbrv: data.results[0].address_components[3].short_name,
          lat: data.results[0].geometry.location.lat,
          lng: data.results[0].geometry.location.lng,
        };
      })
      .catch(function fetchError(error) {
        return error;
      });
  }

Then this is what the object that is returned:

{ approved: 1
  body: "sample comments being made. "
  categories: [{…}]
  created_at: "2020-12-18T19:38:43.000000Z"
  email: "janedoe@gmail.com"
  geocode: {
    county: "Cook County", 
    state: "Illinois", 
    stateAbbrv: "IL", 
    lat: 41.8925085, 
    lng: -87.61616959999999
  },
  id: 7
  image_id: "7"
  is_moderated: 1
  updated_at: "2020-12-21T20:57:04.000000Z"
  zip: "60611"
}

While, I am able to access the body key and all others, even if console.log(object) shows the geocode key to have values when I try to access the key like: object.geocode the value returned is always null. I don't understand why this is happening and any help with getting past this issue is appreciated!

  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Nick Dec 21 '20 at 23:06
  • Sorry, but I don't think so. I am able to get a response & I'm able to see the values being pulled in and saved from the geocoding API into my comment object, which is data originating from another API. When I console.log the whole object it has values, like the last code example, but when I try to access geocode (dot notation or brackets), it returns null. It is only true for the geocode key, all other key/values work fine. – Michele Smolensky Dec 22 '20 at 00:14

0 Answers0