Home > Software design >  Why when I enter 1999-10-17 it submits 1999-10-01 React native?
Why when I enter 1999-10-17 it submits 1999-10-01 React native?

Time:01-03

I'm trying to submit a form with a birthdate. But for one or another reason when I for example enter 1999-10-17 it submits 1999-10-01. It just always removes the last number and puts a 0 before. I've been trying everything I could imagine but nothing works... Why this happens and how can I solve it???

  const [birthdate, setBirthdate] = useState('');
  const [yearB, setYearB] = useState('');
  const [monthB, setMonthB] = useState('');
  const [dayB, setDayB] = useState('');
  const updateBirthdate = () => {
    setBirthdate(`${yearB}-${monthB}-${dayB}`);
  };
  const handleYearBChange = (yearB) => {
    setYearB(yearB);
    updateBirthdate();
  };

  const handleMonthBChange = (monthB) => {
    setMonthB(monthB);
    updateBirthdate();
  };

  const handleDayBChange = (dayB) => {
    setDayB(dayB);
    updateBirthdate();
  };
     <TextInput
        value={yearB}
        onChangeText={handleYearBChange}
        onSubmitEditing={() => yearBInput.current.blur()}
        placeholder="year"
        keyboardType="numeric"
      />
      <TextInput
        value={monthB}
        onChangeText={handleMonthBChange}
        onSubmitEditing={() => monthBInput.current.blur()}
        placeholder="month"
        keyboardType="numeric"
      />
      <TextInput
        value={dayB}
        onChangeText={handleDayBChange}
        onSubmitEditing={() => dayBInput.current.blur()}
        placeholder="day"
        keyboardType="numeric"
      />

CodePudding user response:

You must use useEffect hook to update the birthdate with each rendering, follow the example:

  const updateBirthdate = useCallback(() => {
    setBirthdate(`${yearB}-${monthB}-${dayB}`);
  }, [yearB, monthB, dayB]);

  const handleYearBChange = (yearB) => {
    setYearB(yearB);
  };

  const handleMonthBChange = (monthB) => {
    setMonthB(monthB);
  };

  const handleDayBChange = (dayB) => {
    setDayB(dayB);
  };

  useEffect(() => {
    updateBirthdate()
  }, [updateBirthdate])
  • Related