Home > Software design >  Cant use variable from React Context to access value of object
Cant use variable from React Context to access value of object

Time:04-22

I'm encountering a very strange but seemingly simple problem.

I do have an object called vatRates which looks like this:

const vatRates = {
  "AD": 0.00,
  "CZ": 1.21,
  "RO": 1.19,
  "DE": 1.19,
  "RS": 0.00,
  "RU": 0.00,
  "SE": 1.25,
  "SI": 1.22,
  "SK": 1.20,
  "TR": 0.00,
  "UA": 0.00,
  "US": 0.00
}

an I'm getting a constant called countryCode from my React Context, countryCode has a default value 'DE' and then during initialization of the context changed to "CZ".

countryCode is never null or undefined.

In my component I want to get the value of the countryCode in the vatRates object.

The code should be simple right?

console.log(vatRates[countryCode])

but it only works when countryCode has the default value of "DE" even though the key "CZ" exists on the object.

here a console log of what I'm getting. I really don't know why this simple thing doesn't work.

enter image description here

When I access the object like this manually it works fine.

vatRates["CZ"]

Here is a codesandbox which shows the problem

CodePudding user response:

everything with your context is OK. The problem is there are some whitespaces in value from API.

Just use vatRates[countryCode.trim()] or even better in context:

 const fetchCountryCode = async () => {
      const res = await fetch("https://get.geojs.io/v1/ip/country");
      const countryCode = await res.text();

      return countryCode.trim();
 };
  • Related