waleeeee
waleeeee

Reputation: 119

Getting "TypeError: Cannot read properties of undefined" when trying to access properties of an object

I have a function that grabs data from a local JSON file and renders it. Simple stuff. I do the fetch request within the useEffect hook to fire it only on the first render. Once the data is fetched, it sets it in employees. Once in employees, I use another useEffect to set some other states with data from employees.

  const [employees, setEmployees] = useState<any>([]);

  useEffect(() => {
    fetch("data.json", {
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    })
      .then(function (response) {
        return response.json();
      })
      .then(function (data) {
        setEmployees(data["employees"]);
      });
  }, []);

  useEffect(() => {
    console.log(employees)
    /* set some other state */
  }, [employees]);

/*render list of employees*/

My problem is, I can't actually access the properties within employees. When I console.log the contents of employees, this is what I see, an array of objects

[
  {
      "first_name": "John",
      "last_name": "Doe",
  },
  {
    "first_name": "Jane",
    "last_name": "Doe",
  }]

So to access the properties of the object, i've tried this


employees[0]["first_name"]

employees[0]."first_name"

employees[0][first_name]

employees[0].first_name

In the first two, I get this error


TypeError: Cannot read properties of undefined (reading 'first_name')

While in the last 2 I get this error

Cannot find name 'first_name'

If someone could tell me how to properly access my data it would be much appreciated!

Edit: I'm working in Typescript if that changes anything

Upvotes: 2

Views: 1089

Answers (1)

Wojciech Gadaszewski
Wojciech Gadaszewski

Reputation: 46

Try this one

const [employees, setEmployees] = useState<any[]>([])

link: How to declare array as any: when using UseState hook?

Upvotes: 1

Related Questions