'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.
Solution 1:[1]
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());
}
Solution 2:[2]
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])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Taghi Khavari |
Solution 2 | Paiman Rasoli |