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

192
Visualizações
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 à 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