I have a search page that is linked to the product detail page using the productId
.
In the product detail page, I'm able to use:
const productId = useParams();
Then I have to cross it with a product list, to get the correct Product. For that, I use:
const productSelected = listOfProducts.find(e => e.productId === productId);
The problem is that the productId
that I get from useParams()
, comes as an object. And even though this objects holds the correct productId
, it fails when I'm searching in the list, as e.productId
is a string.
And I'm not able to use double ==
, as the JSLint won't allow me.
I saw some posts saying to use JSON.Stringfy
, but it converts the whole object in string, and not only the value for productId
.
CodePudding user response:
this objects holds the correct productId
It sounds like you just need to destructure it?:
const { productId } = useParams();
This would declare the productId
variable to have the value from the productId
property on the object, not the whole object itself.
It's also worth noting that, by default, URL parameters are strings. If you expect it to be a number then you can convert it as such. Perhaps something like this:
const { productIdParam } = useParams();
const productId = parseInt(productIdParam);
Or, if you're using TypeScript, you can indicate the type when calling useParams
. For example:
const { productId } = useParams<{ productId: Number }>();
In this case productId
will be a Number
.
Based on comments below, it's also important to note something about types when using TypeScript. It only enforces them at design-time, not a run-time. So for example you can declare an interface to have a property that is a Number
, and then use that interface when fetching data from somewhere. But at runtime if the actual property value is a string
then ===
won't work, because the types are wrong. Even though TypeScript said they should be correct, at runtime it's all still JavaScript which doesn't enforce that.