I am trying to display single details of an object inside an array using .find() but I keep getting undefined.
Below is my code on what I was trying to do, when I log id, i get the value but when i log service i get undefined. what could be wrong
export const services = [
{
id: 1,
title: "A good services",
desc: "Lorem300"
},
{
id: 2,
title: "Another good services",
desc: "Lorem300"
},
{
id: 3,
title: "Three good services",
desc: "Lorem300"
},
];
Where I am trying to render the array
import React from "react";
import { useParams } from "react-router-dom";
import { services } from "../constants";
const ServiceDetails = () => {
const { id } = useParams();
const service = services.find((item) => item.id === id);
console.log(id);
return (
<div>
<h2 className="h2 text-accent font-secondary text-[30px] lg:text-[55px]">
{service?.title}
</h2>
</div>
);
};
export default ServiceDetails;
2
Answers
The reason you are getting undefined even though you have the
id
in services, is because you are using triple equals===
. This checks that the value and the type are the same.In your case,
id
from params is a typeof string, andid
in services is a typeof number. So it returns undefined.Solution:
use double equals which only checks the value, not the type.
useParams is returning a string value so you could try one of the following solutions:
Convert the value of
item.id
to stringMore ways to convert to string: What's the best way to convert a number to a string in JavaScript?
Convert the id to type Number
Just use
==
instead of===
since==
will be able to match a sting number with an actual number (Ex:1 == '1'
will beTrue
).You can read up more here: