0

I don't really know how to explain this so I will explain in code

const selectedId = props.match.params.id;
console.log(selectedId); 

The above code prints the correct value for e.g if im on products/2 it prints 2, if I'm on products/3 it prints 3 and so on.

 const product = data.products.find((x) => x._id === 1);
 console.log(product);

Now I have a data array and I am using .find and as you can see x._id === 1, it prints the correct details for object 1 within the array.

 const selectedId = props.match.params.id;
 const product = data.products.find((x) => x._id === selectedId);
 console.log(product);

This prints undefined, if I had to console log selectedId it prints the correct id but when passing it through the find function it returns undefined.

Any help is appreciated thanks

1
  • the problem was that selectedId was a string whereas the id was an integer, and === would return false hence the undefined Commented Aug 17, 2020 at 0:17

1 Answer 1

2

It's most likely because the _id property is a number, but the props.match.params.id is a string. So comparing them with === will return false. Cast the param to a number before comparing:

const selectedId = Number(props.match.params.id)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.