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

214
Views
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 answers
Answer question

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 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!