Code Centrix
Code Centrix

Reputation: 39

Problem accessing object property created using Promise

I am not able to access the returned object property, Please tell me why its returning undefined when data is object and giving correct value.

This is function created to sendHTTPRequest based on data.

import { countryCap } from "./capitalizingFunc.js";

export const sendHTTPRequest = (country) => {
  const capitalisedCountry = countryCap(country);
  return fetch(
    `https://covid-19-coronavirus-statistics.p.rapidapi.com/v1/total?country=${capitalisedCountry}`,
    {
      method: "GET",
      headers: {
        "x-rapidapi-key": "3b0f2e00ebmsh95246403d9540c9p1506d4jsn3c44ce26f745",
        "x-rapidapi-host": "covid-19-coronavirus-statistics.p.rapidapi.com",
      },
    }
  )
    .then((response) => {
      const newResponce = response.json();
      return newResponce;
    })

    .catch((err) => {
      console.error(err);
    });
};

This is constructor class


export class casesDataFetcher {
  constructor(countryName) {
    sendHTTPRequest(countryName)
      .then((response) => {
        return response.data;
      })
      .then((data) => {
        this.country = data.location;
        this.cases = data.confirmed;
        this.recovered = data.recovered;
        this.deaths = data.deaths;
        console.log(this);
        return this;
      });
  }

}

This is execution function

import { casesDataFetcher } from "./casesDataFetcher.js";

export const screenDataShower = (country) => {
  const dataStorage = [];
  const globalInfected = document.querySelector(".infected h2");
  const globalActive = document.querySelector(".active h2");
  const globalDeaths = document.querySelector(".deaths h2");
  const globalRecovered = document.querySelector(".recovered h2");
  const globalCountries = document.querySelector(".countries h2");
  let promise = new Promise(function (resolve, reject) {
    const recordedData = new casesDataFetcher(country);
    console.log(recordedData);
    resolve(recordedData);
  });
  return promise.then((data) => {
    console.log(typeof data);
    console.log(typeof data);
    console.log(data.cases); // NOT WORKING GIVING UNDEFINED
    globalInfected.textContent = `${nn.cases}`;
    globalActive.textContent = data.cases - data.recovered - data.deaths;
    globalDeaths.textContent = data.deaths;
    globalRecovered.textContent = data.recovered;
    globalCountries.textContent = 219;
  });
};

I also tried to convert the data to JSON again but still I was not able to access the property of returned data in screenDataShower

Upvotes: 0

Views: 110

Answers (2)

cuongtd
cuongtd

Reputation: 3192

you're calling sendHTTPRequest inside casesDataFetcher's constructor, from your code there's no guarantee data is resolved when you access it

extract sendHTTPRequest into a new function and wrap into a promise

export class casesDataFetcher {
  constructor(countryName) {
    this.countryName = countryName
  }
   
  fetch = () => {
    return new Promise((res, rej) => {
      sendHTTPRequest(this.countryName)
      .then((response) => {
        return response.data;
      })
      .then((data) => {
        this.country = data.location;
        this.cases = data.confirmed;
        this.recovered = data.recovered;
        this.deaths = data.deaths;
        console.log(this);
        res(this);
      });
    })
  }
}

make screenDataShower function async then you can await data from fetch function in casesDataFetcher, this way it can guarantee data is there when you access it

import { casesDataFetcher } from "./casesDataFetcher.js";

export const screenDataShower = async (country) => {
  const dataStorage = [];
  const globalInfected = document.querySelector(".infected h2");
  const globalActive = document.querySelector(".active h2");
  const globalDeaths = document.querySelector(".deaths h2");
  const globalRecovered = document.querySelector(".recovered h2");
  const globalCountries = document.querySelector(".countries h2");

  const _casesDataFetcher = new casesDataFetcher(country)
  const data = await _casesDataFetcher.fetch()
   
  console.log(typeof data);
  console.log(typeof data);
  console.log(data.cases); // NOT WORKING GIVING UNDEFINED
  globalInfected.textContent = `${nn.cases}`;
  globalActive.textContent = data.cases - data.recovered - data.deaths;
  globalDeaths.textContent = data.deaths;
  globalRecovered.textContent = data.recovered;
  globalCountries.textContent = 219;
};

Upvotes: 1

The problem is that the json method of your response returns a promise instead of plain JSON. So you should change the call of the json method in your sendHTTPRequest function to something like:

.then((response) => {
  const newResponse = response.json().then((jsonResponse) => jsonResponse);
  return newResponse;
})

Upvotes: 0

Related Questions