Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

256
Vistas
React State Storing & Outputting Duplicate Values every re-render

Whenever my page loads I execute the useEffect() function below to retrieve data from firebase and set it to my local state calendarList but every time the page renders it makes a duplicate of the data and pushes is to the state so I have twice as many objects stored. How can I prevent this from happening?

STATE

const [calendarList, setCalendarList] = useState([]);

USE EFFECT - executes on page load

useEffect(() => {
    db.collection("users")
      .doc(userId)
      .collection("calendars")
      .onSnapshot((snapshot) => {
        const calendarArray = [];

        snapshot.forEach((doc) => {
         
          calendarArray.push(doc.data()); push all doc obejects to calendar array
        });
       

        setCalendarList(calendarArray); //set state 
      });
  }, []);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

you can create a custom hook, perhaps.

create a new file and call it as you wish, but gurus out there says it must have to start with use

//useCalendar.js

import {useState, useEffect} from "react"; 

const useCalendar = (userId) => {
  const [calendarList, setCalendarList] = useState([]);

    const addItem = (item) => {
      // use this to add mow items
    };

    const cleanList = () => {
       setCalendarList([]);
    }

    const getItemById = (id) => {
      // use this to get an item
    };

  useEffect(()=> {
    db.collection("users")
      .doc(userId)
      .collection("calendars")
      .onSnapshot(snapshot => {
        const calendarArray =  snapshot && snapshot.map(doc => doc.data());
       
        setCalendarList(calendarArray || []);
      });
  },[userId, list]);

  return {
    calendarList,
    addItem,
    cleanList,
    getItemById
   };

}

export default useCalendar;

now at yow component use it like

const component = () => {
  const { calendarList, addItem, cleanList, getItemById } = useCalendar(userId);
...

}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda