0

I have a split date input (3 different inputs for DD/MM/YYYY) - I've been having some console issues whereby "A component is changing an uncontrolled input to be controlled - likely caused by value changing from undefined to defined."

Basically what I want to do is ensure that if a string value for dateInputValue exists (in this format: "28-08-2022"), then we split it up and pre-populate the fields (this is working).

However, I want to make my code more robust by adding a check that if a string value like so doesn't exist in dateInputValue and it's just an empty string, that the 3 inputs are populated by 3 empty strings ("").

Can anyone suggest an appropriate change to make this happen?

  const [intialDay, initialMonth, initialYear] = dateInputValue.split("-");
  const [day, setDay] = useState(intialDay);
  const [month, setMonth] = useState(initialMonth);
  const [year, setYear] = useState(initialYear);
cts
  • 908
  • 1
  • 9
  • 30
  • You should validate that the value is a valid date first, then proceed to parse it and use the values. See [*How to validate a date?*](https://stackoverflow.com/questions/5812220/how-to-validate-a-date) – RobG Aug 24 '21 at 09:12

1 Answers1

1

You can check if is undefined, set empty string:

const [day, setDay] = useState(intialDay || '');
const [month, setMonth] = useState(initialMonth || '');
const [year, setYear] = useState(initialYear || '');
Fiodorov Andrei
  • 1,778
  • 1
  • 11
  • 26
  • This doesn't fit the OP's criteria. You should first test that *dateInputValue* fits the required pattern, then set variable values accordingly. – RobG Aug 24 '21 at 09:09