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? 😅
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;