Mi problema es que cuando hago clic en mi botón visto, también activa el botón del controlador. ¿Cómo puedo prevenir eso?
Aquí está mi código de botones: HTML:
<div className="bot"> <button id="handler" onClick={() =>{handleClick(0)}}>PICK IT</button> <button id="watched" onClick={() =>{watched()}}>I Already Watched This</button> <a href={data.trailer} target = "_blank" className = "button">WATCH TRAILER</a> </div>Reaccionar y Firebase parte:
function watched(){ const db = getDatabase(app); update(ref(db,"users/" + userInfo + "/watched/" + data.id),{"watched" : "true"}); } function handleClick(val){ if (val >= 250){return 1;} const numberOfUsers = 250; const randomIndex = Math.floor(Math.random() * numberOfUsers); const database = getDatabase(app); const watched = ref(database,"users/" + userInfo + "/watched/" + randomIndex); onValue(watched,(snapshot) =>{ if (snapshot.val().watched === "true"){ handleClick(val+1) } else{ const starCountRef = ref(database, 'movies/'); onValue(starCountRef, (snapshot) => { const data = snapshot.val(); setData(data[randomIndex]) });} })Simplemente agregue el evento dentro de la función onClick={(e) =>{handleClick(e, 0)} . Al agregar este evento, evitará que se active el botón sin un clic real.
Resolví el problema así:
function handleClick(val){ console.log("handlerrr"); if (val >= 250){return 1;} const numberOfUsers = 250; const randomIndex = Math.floor(Math.random() * numberOfUsers); const database = getDatabase(app); const watched = ref(database,"users/" + userInfo + "/watched/" + randomIndex); onValue(watched,(snapshot) =>{ const val = snapshot.val() <-------- THIS LINE ADDED if (val === "true"){ handleClick(val+1) } else{ const starCountRef = ref(database, 'movies/'); onValue(starCountRef, (snapshot) => { const data = snapshot.val(); setData(data[randomIndex]) });} })No estoy seguro, pero probablemente el problema fue cuando onValue funcionó después de que mi función handleClick estaba escuchando mi base de datos y después de cada actualización en mi base de datos se activaba. Así que agregué const val = snapshot.val() ahora solo se está procesando 1 vez.