React.js, using find() to search through the state

I've encountered a problem when trying to find an object in an array of objects(which is also a state) using the find() method. Interestingly when using the same code except when the array of objects is assigned to a constant variable (meaning that it is not a state) everything works fine. I worked on a state as it was, then I worked on a copy of a state but to no avail. Here I'm forwarding the whole React component somewhat simplified for the purpose of this query(originally I'm fetching that array from the server and using one id I want to print other properties of the given object):

import React, { useState } from "react";
import "./App.css";

function About() {
  const [posts, setPosts] = useState([]);

  const post = [
    { userId: 1, id: 1, title: "sunt", author: "Tom" },
    { userId: 1, id: 2, title: "qui est esse", author: "Tom" },
    { userId: 1, id: 3, title: "ea molestias", author: "Tom" },
    { userId: 1, id: 4, title: "eum et est occaecati", author: "Tom" },
  ];

  const button = <button onClick={() => setPosts(post)}>Click me</button>;
  //id of one of the object
  const ItemId = 2;
  console.log(posts);
  //trying to find the object that has id: 2 an then print other
  //  key -values pairs from that prticular object
  let copyState = [...posts];
  console.log(["state copied"], copyState);
  let bla = copyState.find((item) => item.id === ItemId);
  console.log(bla);
  // pritns: {userId: 1, id: 2, title: "qui est esse",author: "Tom"}

  // console.log(bla.title)
  //prints : undefined

  // console.log(bla.author)
  //prints: undefined
  //console.log(typeof 'bla')
  // prints: string

  return (
    <div>
      <h1>About Page</h1>
      {button}
    </div>
  );
}

export default About;

Clicking on the button loads the state and then by uncommenting console.log's errors will start appearing. The first console .log (bla) prints the correct object with has ana id: 3. But then following console.log's are trying to print other properties from that object and that is causing errors. Like I mentioned earlier when doing the same thing but not on a state I was able to access those other properties using dot notation, for example, bla. author and the name 'Tom' was printed on the console. Appreciate any help here, thanks a lot

评论