So i want to render a list of directors in my page by maping then to a
tag i get the directors property from the movie object and i know that it is well written because i can log it and i see the array, the problem is when i try to check it for the length or map it the page crashes and tells me "TypeError: movie.directors is undefined "
<div className="director">
<h3>DIRECTOR{movie.directors.length > 1 ? "S" : ""}</h3>
{movie.directors.map((director) => (
<p key={director.credit_id}>{director.name}</p>
))}
</div>
if i do this:
<h3>DIRECTOR{movie.directors ? "S" : ""}</h3>
and i coment out the maping the page renders fine i also notice that the page crashes and gives me the error.
The error happens only if i refresh the page example i change it from
<h3>DIRECTOR{movie.directors ? "S" : ""}</h3>
{/* {movie.directors.map((director) => (
<p key={director.credit_id}>{director.name}</p>
))} */}
to:
<h3>DIRECTOR{movie.directors.length > 1 ? "S" : ""}</h3>
{movie.directors.map((director) => (
<p key={director.credit_id}>{director.name}</p>
))}
and save the file with out refreshing the page it works fine and the way i want it to but if i refresh the page the the error happens
>Solution :
I believe this is because your initial state is empty object it doesnt have directors.
so you can make it something like:
const [movie, setMovie] = useState({
directors: []
})
So directors is empty array initially