Reputation: 2064
Premise
I have a date that I format and set it as default value to an input type datetime-local. onChange
of the input, I want to format the newly selected date/time and save it in a state. However, it just doesn't work. Below is my code.
DateTime component
import React from "react";
const DateTime = ({ value, onChange }) => {
return <input type="datetime-local" value={value} onChange={onChange} />;
};
export default DateTime;
App.js
import React, { useState, useEffect } from "react";
import DateTime from "./DateTime";
import moment from "moment";
export default function App() {
const [defaultDate, setDefaultDate] = useState("08/08/2020 10:00:00");
// The above static date string comes from a context provider. Here just for the example
const [plannedDate, setPlannedDate] = useState();
const formatPlannedDate = (date) => {
const d = moment(date).format("M/DD/YYYY HH:mm:ss");
return d;
};
const handleOnChange = (value) => {
setPlannedDate(formatPlannedDate(value));
console.log(plannedDate);
};
useEffect(() => {
setDefaultDate(moment(defaultDate).format("YYYY-MM-DD[T]HH:mm:ss"));
}, []);
return (
<div className="App">
<DateTime
value={defaultDate}
onChange={(e) => handleOnChange(e.target.value)}
/>
</div>
);
}
Upvotes: 1
Views: 3537
Reputation: 14891
It did work, but because setPlannedDate
by useState
is asynchronous, so it won't affect immediately. So to see changes, you should put an useEffect
instead
// ...
const handleOnChange = (value) => {
setPlannedDate(formatPlannedDate(value));
};
useEffect(() => {
console.log(plannedDate);
}, [plannedDate])
// ...
Upvotes: 1