mardi 12 novembre 2019

Use async react functional component or if statement

I am developing an app and I need to display a currency based on geological location of the user. If that fails, I want to use the data from my function getCountryInfoByLanguage.

Basically what happens with this code is that it runs, but doesn't wait for the if statement to finish, uses the currency it got from the function, then the if statement finishes and prints the countryCode I want to use. What are my available options? I tried using async/await but I get " Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead."

import convertPrice from "./convertPrice";
import getCountryInfoByLanguage from "./getCountryInfoByLanguage";
import axios from "axios";
export default (language, price) => {
  const { countryCode, currency } = getCountryInfoByLanguage(language);
  let countryCode_;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(position => {
      axios
        .get(
          `http://api.geonames.org/countryCodeJSON?lat=${
            position.coords.latitude
          }&lng=${position.coords.longitude}&username=...`
        )
        .then(response => {
          countryCode_ = response.data.countryCode;
          console.log(countryCode_);
        });
    });
  } else {
    countryCode_ = countryCode;
  }
  console.log(countryCode_);
  const convertedPrice = Math.round(convertPrice(price, currency) * 10) / 10;
  const formattedPrice = convertedPrice.toLocaleString(countryCode_, {
    style: "currency",
    currency: currency
  });
  console.log(formattedPrice);
  return formattedPrice;
};

Aucun commentaire:

Enregistrer un commentaire