Realtime Database duplicates records

Asked

Viewed 14 times

0

Hello,

I’m ranking a game using the Firebase database but every time I "push" the data Firebase makes two records.
Code sample:
The Handlegameover function is invoked when the Gameover variable is changed to true, which occurs only once per game

function HandleGameOver(props){
    const isGameOver = props.isGameOver
    if(isGameOver){
      
      const date = new Date()      
      const data = {
        user,
        points,
        date: `${date.getDate()}/${date.getMonth()+1}/${date.getFullYear()}`
      }
      createRanking(data)

      return (
        <div>
          <Result> Total de Pontos: {points} </Result>
        </div>
      )
    }
    return false
  }

Function to create the ranking:

function createRanking(data){
    firebase.database().ref('ranking').push(data)
      .then(() => {
        console.log('Ranking incluído com sucesso')
      })
      .catch(error => {
        console.log(error)
      })
  }

Result in Firebase:

where-is-game-default-rtdb
   ranking
       -MTqVEGmJ1VvQiBsMb5Z
           date: "18/2/2021"
           points: 100
           user: "gabriel"
       -MTqVEHCy1yt9zYhgVP9
           date: "18/2/2021"
           points: 100
           user: "gabriel"

What might be going on?

  • maybe Handlegameover is running more than once. Try checking if the data already exists in firebase before inserting.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.