Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: movie.directors is undefined

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading