Home > Enterprise >  React how to return a variable so that it renders without giving an error of undefined
React how to return a variable so that it renders without giving an error of undefined

Time:10-20

When I run this, I get the errro

TypeError: Cannot read properties of undefined (reading 'movieTitle')

, but I've already checked and confirmed with the console.log that poplarMovies is getting populated, and popularMovies[0].movieTitle correctly returns a title.

function RateMovies() {

var popularMoviesRef = firebase.database().ref("/popular_movies");

popularMoviesRef.once("value", function(snapshot){

    snapshot.forEach(function(childSnapshot){
        var key = childSnapshot.key;
        var data = childSnapshot.val();

        popularMovies.push({ 
            key: key, 
            movieTitle: data.movie_title, 
            moviePosterLink: data.movie_poster, 
            movieYear: data.movie_year,
            movieGenre: data.movie_genre, 
            movieRating: data.movie_rating
        })
    });
    console.log(popularMovies);
    console.log(popularMovies[0].movieTitle);
});

return (
    <div>
        <p>Rate Movies Here</p>
        <p> {popularMovies[0].movieTitle} </p>
    </div>
)

}

export default RateMovies;

CodePudding user response:

You can use "React.useState" like this:

function RateMovies() {
    
    const popularMoviesRef = firebase.database().ref("/popular_movies");
    const [popularMovies, setPopularMovies] = React.useState([]);
    
    popularMoviesRef.once("value", function(snapshot){
    
        snapshot.forEach(function(childSnapshot){
            var key = childSnapshot.key;
            var data = childSnapshot.val();
    
            setPopularMovies(currMovies => [...currMovies,{ 
                key: key, 
                movieTitle: data.movie_title, 
                moviePosterLink: data.movie_poster, 
                movieYear: data.movie_year,
                movieGenre: data.movie_genre, 
                movieRating: data.movie_rating
            }])
        });
        console.log(popularMovies);
        console.log(popularMovies[0].movieTitle);
    });
    
    return (
        <div>
            {popularMovies.map(movie => <React.Fragment>
                 <p>Rate Movies Here</p>
                 <p> {movie.movieTitle}</p>
             </React.Fragment>)}
        </div>
    )
 }
    
 export default RateMovies;
  • Related