Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
Cant use variable from React Context to access value of object

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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();
 };
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!