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

173
Visualizações
Show counter onChange input box with a current defaultValue in React

How do I get the value to be the inital value first form the data of the API and then change when the user starts typing or deleting text?

import React, {useState} from 'react'

const MyInput = () => {
  const [counter, setCounter] = useState(0)

  const initial = dataFromApi.length

  const total = 1000

  const counterChange = (e) => {
    setCounter(initial.length + e.target.value.length)
  }

  return(
    <>{counter}/{total}<input defaultValue={dataFromApi} onChange={counterChange}/></>
  )

}

export default MyInput

https://codesandbox.io/s/compassionate-napier-3nekx?file=/src/App.js

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

0

Pass the initial length to the useState hook

const initial = dataFromApi.length
const [counter, setCounter] = useState(initial)

If you expect your API data to change you could use a useEffect hook to reset the length state when API data changes

useEffect(() => {
  setCounter(dataFromApi.length);
}, [dataFromApi.length]);

and there's no need to add the initial value in the onChange handler if you want to show the current length of the entered text

setCounter(e.target.value.length)

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