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

259
Visualizações
React, show array element according to timestamp

The feature I would like to implement is that the React component shows the task that would be taking place according to the timestamps of the data that are in the data array.

Each of the elements of the array has two timestamps, the timestamp of when the task is started and when the task is finished.

However, unfortunately I don't know how I could make the component dynamically show the task that will be executed.

That is, if there is a task to be executed, it would show the task that is being started, otherwise, it doesn't show the task and waits until the next task in the array starts so that it can show it.

I hope I'm not being confused 😬

import React, { useEffect, useState } from 'react'

const data = [
  {
    id: 1,
    title: "Read book"
    start: "2021-12-30T14:41:39+0000",
    end: "2021-12-30T15:41:39+0000"
  },
  {
    id: 2,
    title: "Clean desk"
    start: "2021-12-30T17:01:39+0000",
    end: "2021-12-30T17:24:39+0000"
  }
]

const App = () => {
  const [currentTask, setCurrentTask] = useState(undefined)
  
  useEffect(() => {
    setCurrentTask(getCurrentTask())
  }, [currentTask])

  const getCurrentTask = () => {
    return data ? data.find((task) => new Date(data.start).getTime() <= Date.now()) : undefined
  }

  return (
    <>
     {currentTask ? <div>{currentTask.title}</div> : <div>No current task</div>}
    </>
  )
}

How could I implement this? 😅

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can do this by using setInterval or useInterval to periodically check the data and update the state based on start datetime, I put the useInterval code from the library here to see how to use setInterval correctly in react:

useInterval:

import React, { useEffect, useRef, useLayoutEffect } from "react";

export function useInterval(callback, delay) {
  const savedCallback = useRef(callback);

  useLayoutEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  useEffect(() => {
    if (!delay && delay !== 0) {
      return;
    }

    const id = setInterval(() => savedCallback.current(), delay);

    return () => clearInterval(id);
  }, [delay]);
}

App Component:

import React, {useState} from "react";
import useInterval from "./useInterval";

const data = [
  {
    id: 1,
    title: "Read book",
    start: "2021-12-30T19:33:20",
    end: "2021-12-30T19:20:20",
  },
  {
    id: 2,
    title: "Clean desk",
    start: "2021-12-30T19:31:39",
    end: "2021-12-30T19:25:39",
  },
];

const App = () => {
  const [currentTask, setCurrentTask] = useState(undefined);
  useInterval(
    () => {
      const currentTask = getCurrentTask();
      setCurrentTask(currentTask);
    },
    // Delay in milliseconds or null to stop it
    60000
  );

  const getCurrentTask = () => {
    return data
      ? data.find((task) => {
          const startTime = new Date(task.start).getTime();
          const endTime = new Date(task.end).getTime();
          const now = Date.now();

          return startTime <= now && endTime >= now;
        })
      : undefined;
  };

  return (
    <>
      {currentTask ? (
        <div>{currentTask.title}</div>
      ) : (
        <div>No current task</div>
      )}
    </>
  );
};

export default App;
about 4 years ago · Juan Pablo Isaza Relatório
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