I have a component called Date with three variables. I also have a function called setCurrentTimes that is supposed to update the variables each time it is called with the current values.
I call the function inside react’s useEffect that has no dependencies to update the variables on the component mount.
Here is the date component.
const Date = () => {
var currentDate;
var currentTime;
var amOrPm;
const setCurrentTimes = () => {
currentDate = moment().format("d MMMM YYYY");
currentTime = moment().format(" h:mm:ss ");
amOrPm = moment().format("a");
};
useEffect(() => {
setCurrentTimes();
}, []);
return (
<div className="Date flex__container-v">
{amOrPm === "pm" ? (
<div className="Moon__icon flex__container">
<img src={Assets.Moon} alt="Moon Icon" />
<p className="p__poppins Date__greeting">Good Evening</p>
</div>
) : (
<div className="Sun__icon flex__container">
<img src={Assets.Sun} alt="Sun Icon" />
<p className="p__poppins Date__greeting">Good Morning</p>
</div>
)}
<div className="Date__btm flex__container">
<p className="p__poppins">{currentDate}</p>
<p className="p__poppins">{currentTime}</p>
</div>
</div>
);
};
The component returns different things depending on the variables. However, it is not working as expected. When I try to log out the variables inside the return statement I get undefined.
I don’t get what I am doing wrong.