I can't figure out where is the problem

useEffect fires after the first render, on the initial render you are providing a default value so “companies” is an empty array.

In your map function you’re trying to map an empty array and calling .id and .name on an object that doesn’t exist. It’s like doing this:

const companies = []

companies.map(company => {

console.log(company.id) // error since company is undefined.

})

There are a couple ways to solve the problem.

1) put in a guard to make sure that companies.length > 0 before mapping.

{companies.length > 0 && companies.map(company => {

}}

2) change your useEffect to a useLayoutEffect so that it fires and sets “companies” before the first render.

Best approach would be #1 because a useLayoutEffect would delay the render if your API times out.

/r/reactjs Thread