The UndertakerGL
The UndertakerGL

Reputation: 75

Firebase value to localstorage

I am a beginner learning Javascript and I am making a game.
The highscore is set into localstorage at this moment. Now I'm learning a firebase database, and the highscore is updating to firebase, but when I refresh it start again at 0 because it updates when score > highscore.

I want to set the localstorage highscore to the firebase value when I reloading the page.

I tried the following:

localStorage.setItem("highscore", firebase.database().ref('/score/currentHighscore').once('value'));

but this does't work. Any help?

My highscore in firebase is under score -> currentHighscore.

Upvotes: 1

Views: 2050

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83163

As explained in my comment above, the once method is asynchronous, so you should do something like:

return firebase.database().ref('/score').once('value').then(function(snapshot) {
    var highScore = snapshot.val().currentHighscore; //maybe test here it is not null
    localStorage.setItem("highscore", highScore);
});

I would advice you have a look at https://firebase.google.com/docs/database/web/read-and-write#read_data_once

Upvotes: 1

Related Questions