Cannot read property of undefined when using react hooks
12,247
Solution 1
You response data mybe a list or undefined
you need to do like this:
setMovies(pre => ({
...pre,
movies: data || []
}))
Solution 2
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] })
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on June 04, 2022Comments
-
Admin about 2 years
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