Cannot read property of undefined when using react hooks

Tommmm picture Tommmm · May 22, 2019 · Viewed 7.7k times · Source

I'm getting the error "Cannot read property 'map' of undefined" but can't work out why - map will not work because 'movies' is undefined. Can you see what I'm doing wrong? Many thanks.


const Dashboard = () => {
  const discoverUrl = 'https://movied.herokuapp.com/discover';
  const [movieList, setMovies] = useState({ movies: [] });

  useEffect(() => {
    const getAllMovies = () => {
      fetch(discoverUrl)
        .then(response => response.json())
         .then(data => setMovies(data))
        }
        getAllMovies()

      }, [])

  return (
    <ul>
      {movieList.movies.map(movie => (
        <li>
          <p>{movie}</p>
        </li>
      ))}
    </ul>
  );
}

export default Dashboard```

TypeError: Cannot read property 'map' of undefined

Answer

blastz picture blastz · May 22, 2019

You response data mybe a list or undefined you need to do like this:

setMovies(pre => ({
  ...pre,
  movies: data || []
}))