Issue
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.
Solution
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}</> : null;
};
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>
Answered By - Phil
Answer Checked By - - Terry (ReactFix Volunteer)