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

193
Vistas
How to track each time a new setInterval on an array of elements arriving from the API?
  1. I receive data from the API, and I save only objects with status 1 or 2 to the state.

`const [items, setItems] = useState([]);

      const handleOnFetchData = useCallback((data) => {
        setItems(
          data.results.filter(
            (report) => report.status === 1 || report.status === 2
          )
        );
      }, []);`
  1. Objects change their status over time. And you need to track it every 5 seconds in the interval.

How I do:

  1. There is a useEffect that depends on the state with items, and if the state is not empty, then iterates over the state and calls the monitoringItem function for each element

`let interval;

  useEffect(() => {
    if (items.length > 0) {
      items.forEach((report, i) => {
        interval = setInterval(() => {
          monitoringItem(report.record_id);
        }, 5000);
      });
    } else {
      clearInterval(interval);
    }
  }, [items]);`
  1. the monitoringItem function sends a request every 5 seconds and checks the status of the item. if the status is anything other than 1 or 2, then stop the interval and remove that item from the state.

    const monitoringItem = useCallback(
          async (id) => {
            const response = await API.get(`/reports/${id}`);
    
            const monitoredReport = response.data.results[0];
    
            if (monitoredReport.status !== 2 && monitoredReport.status !== 1) {
              clearInterval(interval);
              setItems(
                items.filter((rep) => rep.record_id !== monitoredReport.record_id)
              );
            }
          },
          [items]
        );
    

Question and problem: How can I hang my own setInterval for each item when adding. Now everything is fine with 1 item. but adding others breaks everything.

about 4 years ago · Juan Pablo Isaza
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