I would like to render a component on my react-app at a given time eg 6.00PM 27 October 2022. For example, a form would be released for signing up at that from that given time onward. This time stamp would be stored in my database, which will be queried by the react-app. How do I accomplish this in React with JavaScript?
I have thought of comparing Date() objects. Eg. get the current time and compare it to a Timestamp converted to Date() queried from the firebase firestore. However, I am unsure how I would use UseEffect to update the current time continuously for the comparison. Is this approach correct? If not, I would appreciate some suggestions.
CodePudding user response:
Compare the current time to the stored timestamp and set a timeout with the difference. In the timeout callback, toggle some state to display the component
import { useEffect, useState } from "react";
const Scheduled = ({ timestamp, children }) => {
const [isEnabled, setEnabled] = useState(false);
useEffect(() => {
const diff = timestamp - Date.now();
const timer = setTimeout(() => {
setEnabled(true);
}, diff);
return () => {
clearTimeout(timer);
};
}, [timestamp]);
return isEnabled && children;
};
If the current time has passed the timestamp, this will show immediately.
You could then use this component like this
<Scheduled timestamp={timestampFromDb}>
<SomeFormComponent />
</Scheduled>
CodePudding user response:
If your intent is for the component to be rendered without a page refresh, then you could use an interval within useEffect
to the effect of
const [visible, setVisible] = useState(false);
useEffect(() => {
const interval = setInterval(() => {
if (new Date() > serverDate) {
setVisible(true);
}
}, 10000);
return () => clearInterval(interval);
}, []);
Change 10000
to whatever interval you want to check at.