Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

189
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda