Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property of undefined when using react hooks

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
like image 601
Tommmm Avatar asked May 22 '19 11:05

Tommmm


People also ask

How do you fix cannot read property of undefined in react?

The "Cannot read property 'props' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.

Can react hooks be called conditionally?

React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render.


2 Answers

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

setMovies(pre => ({
  ...pre,
  movies: data || []
}))
like image 101
blastz Avatar answered Oct 18 '22 18:10

blastz


When you set state which is setMovies(data), movieList will be equal to data. So you will lose movies property in movieList(there will be no movieList.movies).

So either initiate state like this

const [movieList, setMovies] = useState([]);

and do setMovies(data).

Or else set state like

setMovies({ movies: [...data] })
like image 3
Nayan shah Avatar answered Oct 18 '22 18:10

Nayan shah