-1

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;

greatkene
  • 1
  • 3

2 Answers2

1

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, and id in services is a typeof number. So it returns undefined.

Solution:

const service = services.find((item) => item.id == id);

use double equals which only checks the value, not the type.

Arcanus
  • 642
  • 5
  • 20
-1

useParams is returning a string value so you could try one of the following solutions:

  1. Convert the value of item.id to string

    const service = services.find((item) => `${item.id}` == id);
    

    More ways to convert to string: What's the best way to convert a number to a string in JavaScript?

  2. Convert the id to type Number

    const service = services.find((item) => item.id === Number(id));
    
  3. Just use == instead of === since == will be able to match a sting number with an actual number (Ex: 1 == '1' will be True).

    You can read up more here:

Craig
  • 1
  • 2