Matt T. Matt T. - 2 months ago 9
Javascript Question

Two buttons delete each other's set data

I have two buttons which adds one to the

HomeScore
variable and
GuestScore
variable. I got each button to control their respective database entries, but whenever I press the home score button, it deletes the guest score entry in the database.

It does this in reverse too; whenever I press the guest score button, it deletes the home score value.

Pastebin here

Answer

Matt, You are updating the same reference for both home and guest scores. Take a look at the following two lines:

var homeScoreRef = firebase.database().ref("scores/");
var guestScoreRef = firebase.database().ref("scores/");

These references are the exact same. If you set one of them, then set the other, the first one will be overwritten.

In your following code, you set those references to their respective values, however, remember that since you made the references point to the exact same piece of the database, you are just overwriting your values with whichever button was pressed.

homeScoreRef.set({
    home: HomeScore
});

and:

guestScoreRef.set({
    guest: GuestScore
});

Try something like this out:

var homeScoreRef = firebase.database().ref("scores/home/");
var guestScoreRef = firebase.database().ref("scores/guest/");

or alternatively you could do:

var homeScoreRef = firebase.database().ref("scores/").child("home");
var guestScoreRef = firebase.database().ref("scores/").child("guest");

Update:

After you change the references, then change your set() calls to look like this:

homeScoreRef.set(
    HomeScore
);

guestScoreRef.set(
    GuestScore
);

This should get rid of the extra /home and /guest in your references.

Also, when you say homeScoreValueRef.on, where are you getting this? Where is this reference being created? Because I think you meant to do homeScoreRef.on, correct? I think this is why you get the NaN error.

If you have more code than what you have shown in your Pastebin, then make sure you update it to reference the proper references, but overall, I believe this is your error.