Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

105
Visualizações
Firebase (reactjs) reads from database too many times

I'm reading from my firebase realtime database when my component loads to update a state with the returned data. Whenever the component loads, it gets the data from the database 8 times, and this causes React to give an error since the state is updated too many times in quick succession.

I've tried using both the onValue listener and the get function, and they both do the same thing on page load. If instead, I do not call them on page load, and either onValue or get runs manually or from the database being updated, it runs only once as expected.

The component:

export default function FoodItem(props) {
    const [foods, setFoods] = useState()
    const db = getDatabase()

    // creating the onValue listener (below) creates the same issue

    // const mealRef = ref(db, (props.userId + "/" + props.date + "/" + props.meal))
    // onValue(mealRef, (snapshot) => {
    //     const data = snapshot.val()
    //     console.log(data)  
    //     setFoods(data)
    // })

    useEffect(() => {
        console.log("getFoods")
        const dbRef = ref(getDatabase())
        
        get(child(dbRef, (props.userId + "/" + props.date + "/" + props.meal))).then((snapshot) => {
            if (snapshot.exists()) {
                console.log(snapshot.val())
                // setFoods(data)
            } else {
                console.log("No data available")
            }
        }).catch((error) => {
            console.error(error)
        })
    }, [])

    return (
        ...
    )
}

The console output from the code above

If instead of using useEffect, I call get with a function (for example, with onClick, it only gets the data once as expected:

    function getFoods() {
        console.log("getFoods")
        const dbRef = ref(getDatabase())
        
        get(child(dbRef, (props.userId + "/" + props.date + "/" + props.meal))).then((snapshot) => {
            if (snapshot.exists()) {
                console.log(snapshot.val())
                // setFoods(data)
            } else {
                console.log("No data available")
            }
        }).catch((error) => {
            console.error(error)
        })
    }

How do I make it only run once when the component loads?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda