Reputation: 584
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.
Upvotes: 0
Views: 846
Reputation: 1122
Short answer: use state in order to fix this.
Longer answer:
You are probably expecting useEffect to run before render, but this is not the case.
useEffect is always called after the render phase of the component. Your ParentComponent consists of Input, Input & ChildComponent.
In your case you are trying to display variables that are not yet set. If you were to use State instead of variables your UI would re-render after setting these states. Since you're using variables your UI wont re-render causing it to always display the initial values (which is empty).
simplified example:
const Date = () => {
const [currentDate,setCurrentDate] = React.useState();
useEffect(() => {
setCurrentDate(moment().format("d MMMM YYYY"));
}, []);
return (
<div className="Date flex__container-v">
<div className="Date__btm flex__container">
<p className="p__poppins">{currentDate}</p>
</div>
</div>
);
};
Upvotes: 1