Below is my own the Timer Component
: (React-Native)
element - contains information about creation date
The timer when loaded at the beginning counts down from 300s
to 0
and shows Expired
function Timer({ element }) {
// I determine the element's validity for 5 minutes (300000 ms)
const endTime = Number(element.item.created_at) + 300000
// Field containing the value displayed in the component + initialValue
const [textTimer, setTextTimer] = useState(() => {
const diff = endTime - Date.now()
if (diff <= 0) {
return 'Expired'
}
else {
return (diff / 1000).toFixed(0)
}
})
// Code that is executed every 1s
useEffect(() => {
const diff = endTime - Date.now()
let interval = null
if (diff > 0) {
interval = setInterval(() => {
setTextTimer(prev => prev - 1)
}, 1000);
}
else {
setTextTimer('Expired')
}
return () => clearInterval(interval);
}, []);
return (
<View>
<Text>{textTimer}</Text>
</View>
)
};
But something is wrong with it.
Refreshing does not occur after 1 second (it is variable)
How do you get a display equal to the specified time? Make this Timer work like real time