I've got a split date component (with 3 seperate inputs for day, month & year) - the component looked like so:
const DateInput = ({ name, onValueChange, dateInputValue }: Props) => {
const [day, setDay] = useState("");
const [month, setMonth] = useState("");
const [year, setYear] = useState("");
const storedDateValue = useRef();
console.log("Base date value: " + dateInputValue);
const changeDate = useCallback(
(birthday) => {
onValueChange(birthday);
},
[onValueChange]
);
useEffect(() => {
if (day !== "" && month !== "" && year !== "") {
const dateValue = `${day}-${month}-${year}`;
if (storedDateValue.current !== dateValue) {
storedDateValue.current = dateValue;
changeDate(dateValue);
}
}
}, [day, month, year, changeDate]);
return (
<StyledInputGroup>
<label htmlFor={`${name}_day`}>
<span>Day</span>
<StyledInput
type="text"
maxLength="2"
name={`${name}_day`}
id={`${name}_day`}
label="Day"
value={day}
onChange={(e) => setDay(e.target.value)}
/>
</label>
<label htmlFor={`${name}_month`}>
<span>Month</span>
<StyledInput
type="text"
maxLength="2"
name={`${name}_month`}
id={`${name}_month`}
label="Month"
value={month}
onChange={(e) => setMonth(e.target.value)}
/>
</label>
<label htmlFor={`${name}_year`}>
<span>Year</span>
<StyledInput
type="text"
maxLength="4"
name={`${name}_year`}
id={`${name}_year`}
value={year}
onChange={(e) => setYear(e.target.value)}
/>
</label>
</StyledInputGroup>
);
};
But I made the following change so that if an initial value was present, then the date inputs would be pre-populated by updating the useState hook like so:
const [intialDay, initialMonth, initialYear] = dateInputValue.split("-");
const [day, setDay] = useState(intialDay);
const [month, setMonth] = useState(initialMonth);
const [year, setYear] = useState(initialYear);
This meant that we set the day/month/year to the initial value as opposed to an empty string. However, when the fields are blank, and values added, they don't appear to be picked up and results in validation still firing an empty input. When I log to the console it appears that the setState hook isn't working unless working off an intialDay/month/year value. Can anyone spot where I'm going wrong?