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

216
Vistas
React - saved value always reads as NULL

I have this component which has been passed a parameter in its route from another component. I save the value in a cost in order to use it.

  const params = useParams()
const id = params.id; 

if I click on the Card component it would navigate me to a different route which has the component card details

when using console.log(id) I get the proper value.

now I have this array of objects from back-end and there is where I need the ID parameter for compare.

const [state, setState] = useState<any>(store.getState().perfumeState.perfumes);

Here is the array of perfumes which is stored in store of redux

So basically What I am trying to do is find the specific perfume object with the given ID and for that I used:

 var result = state.filter(obj => {
        return obj.id === id // <------- Returns `NULL` // return obj.id === 2 // <-------- Returns correct value
      })

here I have an issue. while I hard-code a number I get the proper result, however, when I use the id value it returns null. also, Instead of getting an object I get an array of one object each time.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Route parameters from useParams always have string values (or are undefined). So if the id field on your objects has type number, then equality checks with strict equality operator (===) will never pass.

You can fix this by using either the normal equality operator (==) or by casting id (from params) to a number.

Either:

const result = state.filter(obj => obj.id == id);

or:

const result = state.filter(obj => obj.id === Number(id));

Would recommend casting to a number and keeping strict equality (especially since your eslint settings will probably warn you about using the normal equality operator).


As for getting a single object rather than an array, you can use the find method (instead of filter), which will return the first element satisfying your condition or undefined. Like this:

const result = state.find(obj => obj.id === Number(id));
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