Home > OS >  React - saved value always reads as NULL
React - saved value always reads as NULL

Time:11-29

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.

CodePudding user response:

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));
  • Related