Clicking a +/- button should increment or decrement the date by one day. I am having trouble getting the two functions to work for a click event. Why is the error message
newDate is undefined
coming up when the variable is defined and the state has been set? I am just working on the 'minus' button for now:
import React from "react";
import ReactDOM from "react-dom/client";
import { useState } from "react";
function App() {
const date = new Date("june 21 2027");
const [newDate, setNewDate] = useState(date);
const [count, setCount] = useState(1);
return (
<div>
{/* <div>
<button>-</button>
<span>Step : Step 1</span>
<button>+</button>
</div> */}
<div>
<button
className={"minus"}
id={1}
onClick={function () {
setCount(function (c) {
return c - 1;
});
setNewDate(function (d) {
d.setDate(date.getDate() - count);
return;
});
}}
>
-
</button>
<span>Count : {count}</span>
<button
className={"plus"}
id={2}
onClick={function () {
return setCount(function (c) {
return c + 1;
});
}}
>
+
</button>
</div>
<span>Today is {`${newDate.toDateString()}`}</span>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
Returning setNewDate
into the setCount
function didn't work.
You are doing setCount()
and setNewDate()
but state updates are not immediate. You are still accessing the previous value of the count.
You're calling setNewDate
with no return value (return;
), which breaks the state update.
You're modifying the original date
object (date.setDate()
), which may lead to unexpected results.
In the onClick
function I'm calling setCount
. In setCount
I'm caching the updated count. I'm caching initialDate
as a Date
object which is date
according to your code.
On the cached date I'm calling the pre-defined setDate
and I'm calling the predefined getDate
on initial date and add the updated count to that date.
Now I'm updating the date newDate
by calling setNewDate
and passing the cached updatedDate
. Finally I return the updated count so that it updates the count state variable. () => {}
is the arrow function syntax from JavaScript 2015 (ES6).
onClick={() => {
setCount((c) => {
const newCount = c - 1;
const updatedDate = new Date(baseDate);
updatedDate.setDate(baseDate.getDate() + newCount);
setNewDate(updatedDate);
return newCount;
});
}}