'find method is not working in my react application
function ProductScreen(props) {
console.log(props.match.params.id);
const product = data.products.find((x) => x.id === props.match.params.id);
console.log(product);
return (
<div>
<h1>{product}</h1>
</div>
);
}
In the console of the product, it says undefined.
Solution 1:[1]
I had a similar problem with my React App. When I deployed it to Host server as "... pageData.find((x) => x.id === parseInt(id));
" it returned undefined
, but it worked fine in local server. I doubt it and changed to ==
and it worked fine. There might be a bug or something.
Solution 2:[2]
function ProductScreen(props){
console.log(props.match.params.id);
const product = data.products.find( x => x._id === props.match.params.id);
console.log(product);
return <div>
<h1>{product.name}</h1>
</div>
}
This is working fine you can give product.name or product.id..
Solution 3:[3]
You need to make sure that you are comparing the same data type between the data.products and props.match.params.id.
The datatype of props.match.params.id is a string. Hence, the data.products.id should be also a string.
Solution 4:[4]
Because props.match.params.id is string and x.id is number that is why it is undefined you should convert props.match.params.id to number
function ProductScreen(props) {
const id = Number(props.match.params.id);
const product = data.products.find((x) => x.id === id);
return (
<div>
<h1>{product}</h1>
</div>
);
}
Solution 5:[5]
Use x._id.toString()===match.params.id
Solution 6:[6]
const product = data.products.find((x) => x._id == props.match.params.id);
Use ==
instead of ===
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Henry Ecker |
Solution 2 | |
Solution 3 | jem |
Solution 4 | Shukhrat Mamadaliev |
Solution 5 | cizario |
Solution 6 | Shizzen83 |