Below I've included the relevant code. You can see the page in action at https://nextflix-96831.web.app (sign in with google then hit the like or dislike button). Basically, whenever you hit the like or dislike button, data is pulled from the database twice with the first data immediately being replaced by the second data.
I think this has something to do with my setRender, but I'm not sure since I'm new to react.
import React, { useState, useEffect } from 'react';
import './App.css';
import firebase from 'firebase/compat/app';
import 'firebase/database';
import 'firebase/firestore';
import './Menu/Menu.css';
function RateMovies() {
const popularMoviesRef = firebase.database().ref("/popular_movies");
const [popularMovies, setPopularMovies] = React.useState([]);
var [render, setRender] = React.useState(1);
useEffect(() => {
popularMoviesRef.once("value").then(function(snapshot){
var newArray = []
snapshot.forEach(function(childSnapshot){
var key = childSnapshot.key;
var data = childSnapshot.val();
newArray.push({
movieTitle: data.movie_title,
moviePoster: data.movie_poster,
})
});
setPopularMovies([...popularMovies, ...newArray])
});
}, [render]);
var index = Math.floor(Math.random() * (1000 + 1));
var movie = popularMovies[index];
console.log(movie);
const auth = firebase.auth();
var db = firebase.firestore();
var user_id = auth.currentUser.uid;
function likedMovie() {
var genres = movie.movieGenre.split(',');
db.collection('users').doc(user_id).update({
"Rated.liked": firebase.firestore.FieldValue.arrayUnion({
movieTitle: movie.movieTitle,
moviePoster: movie.moviePoster,
})})
.then(function(){
setRender(render + 1);
});
index = Math.floor(Math.random() * (1000 + 1));
movie = popularMovies[index];
}
return (
<div class="rate-background">
<div className="rate-title"> {movie?.movieTitle} </div>
<button onClick={likedMovie}> Like</button>
<img class="rate-image" src={`${movie?.moviePoster}`} />
</div>
)
}
export default RateMovies;