Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
Input field is always one value behind what Ive typed

I am trying to build a date input for the first time. I have the task of making sure the input displays a leading 0 if the month or day are set to a single digit. The issue Im having is when a value is entered it doesnt make it to the next handler until the next time i type into a field. I believe this is because Im passing the value through the state. But im not sure how to have the state readily available to send right after the user types in the field:

State:

  const [date, setDate] = useState({ day: "", month: "", year: "" });

My date input consist of three separate inputs for mon/day/year ill only show month here:

<div className="nh-date">
          <Input
            onChange={dateChange("month")}
            value={date.month}
            className={`nh-mon ${!!error && "error"}`}
            name="month"
            id="mon"
            maxLength={2}
            type="number"
            selectTextOnFocus={true}
          />
          <span className="sep">/</span>

UseEffect:


useEffect(() => {
    if (!!effectiveDate) {
      const effectiveMoment = !!effectiveDate ? moment.parseZone(effectiveDate) : {};
      setCalendarDate(effectiveMoment);
    }

    if (!!startDate) {
      const [month, day, year] = startDate.split("/");
      let shortYear = year.slice(-2);
      setDate({ ...date, day: day, month: month, year: shortYear });

      const newDate = `${month}/${day}/${year}`;
      if (moment(newDate).isValid()) {
        debounceCallback(handleDateInputChange, newDate);
        setError(false);
      } else {
        setError(true);
      }
    }
  }, [startDate, effectiveDate]);

My onChange handler looks like this:

     const dateChange = (field: string) => (e: any) => {
        // format to fit
        let value = e.target.value;
        let d = { day: "", month: "", year: "" };
        if (value.length < 2) {
          value = "0" + value;
        } else {
          //remove extra leading 0's
          value = value.slice(-2);
        }
    
        setDate({ ...date, [field]: value });
        const newDate = `${date.month}/${date.day}/20${date.year}`;
        setStartDate(newDate);
      };

Once I type into the field debounceCallback(handleDateChange, newDate); receives the newDate but not as it is currently shown it sends the initial or previous value. I still struggle with handling input in the state im not sure how to work around this any advice would be helpful. Thank you!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

in useEffect your date is updated and you call callback with new date

const dateChange = (field: string) => (e: any) => {
    // format to fit
    let value = e.target.value;
    let d = { day: "", month: "", year: "" };
    if (value.length < 2) {
      value = "0" + value;
    } else {
        //remove extra leading 0's
      value = value - 0;
    }

    setDate((prevState) => {
        return { ...prevState, [field]: value };
    });
}

useEffect(() => {
  const newDate = `${date.month}/${date.day}/${date.year}`;
  if (moment(newDate).isValid()) {
    debounceCallback(handleDateChange, newDate);
    setError(false);
  } else {
    setError(true);
  }
}, [date, //rest dependencies]);
about 4 years ago · Juan Pablo Isaza Relatório

0

Calling setState() in React is asynchronous, for various reasons (mainly performance). Under the covers React will batch multiple calls to setState() into a single state mutation, and then re-render the component a single time, rather than re-rendering for every state change.

I think you get previous value for Month 
setDate({ ...date, [field]: value }); not immediately update the state.

const dateChange = (field: string) => (e: any) => {
    // format to fit
    let value = e.target.value;
    let d = { day: "", month: "", year: "" };
    if (value.length < 2) {
      value = "0" + value;
    } else {
        //remove extra leading 0's
      value = value - 0;
    }

    setDate({ ...date, [field]: value });

    const newDate = `${value}/${date.day}/${date.year}`;
   
    if (moment(newDate).isValid()) {
      debounceCallback(handleDateChange, newDate);
      setError(false);
    } else {
      setError(true);
    }
  };
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda