Home > Net >  TypeError: movie.directors is undefined
TypeError: movie.directors is undefined

Time:12-05

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

CodePudding user response:

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

CodePudding user response:

One thing to add here is, it is now a good choice to add an empty array as an initial state.

Reason

  • You are fetching movies and in the meantime, you want to show a loader as a symbol of loading, then instead of using another state variable loading to show this, you can simple have an if condition while returning that,

    return movies === null ? :

  • Moreover, if you do not have any item after fetching, the how could you indicate that there are no items in the list, as you already have taken the list as empty array instead of null.


Solution

It is suggested to use a null check all the time, like

{movie?.directors.map((director) => (
    <p key={director.credit_id}>{director.name}</p>
))}

or

{movie && movie.directors.map((director) => (
    <p key={director.credit_id}>{director.name}</p>
))}

or to show <Loader/> while loading

{movie=== null ? <Loader/> : movie.directors.map((director) => (
    <p key={director.credit_id}>{director.name}</p>
))}

These all will only render content if present and prevent any null or undefined content rendering

  • Related