Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!