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

171
Visualizações
How to set default attribute when set multiple attribute in single state in useState in react
  const [currentTime, setTime] = useState();
  const [input, setInput] = useState({
    title:"",
    description:"",
    time:currentTime,
  });
function handleOnclickAdd(){
    setTime(new Date().toLocaleTimeString())
}

here when I am do console.log(currentTime) show perfect output but when i do console.log(input) in that show output time:undefine. then How to set time as current time.

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

0

when the input state is initializing the currentTime is undefined so if you want to change that to another value just change the value to whatever you want like this:

  const [currentTime, setTime] = useState();
  const [input, setInput] = useState({
    title: "",
    description: "",
    time: new Date().toLocaleTimeString()
  });
  function handleOnclickAdd() {
    setTime(new Date().toLocaleTimeString());
  }
about 4 years ago · Juan Pablo Isaza Relatório

0

because at first stage currentTime is null so you should use useEffect function to handle this :

  const [currentTime, setTime] = useState();
  const [input, setInput] = useState({
    title:"",
    description:"",
   time:currentTime,
   });
 function handleOnclickAdd(){
    setTime(new Date().toLocaleTimeString())
 }
 useEffect(() => {
  setInput(...input , [time] : currentTime);
},[currentTime])
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