Home > Mobile >  How can I prevent the button from triggering the other button when I click it? &React
How can I prevent the button from triggering the other button when I click it? &React

Time:12-17

My problem is when I click my watched button, it also triggers handler button. How can I prevent that?

Here is my buttons code: 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>

React & Firebase part:

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])
            });}
        })
        

CodePudding user response:

I solved the problem like this:

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])
            });}
        })

I am not sure but probably problem was when onValue worked after that my handleClick function was listening my database and after each update on my database it was triggering. So I added const val = snapshot.val() now it is only rendering 1 time.

CodePudding user response:

Just add event inside onClick function onClick={(e) =>{handleClick(e, 0)}. Adding this event you will prevent triggering button without actual click.

  • Related