I am a starter on React! Just learning right now
How can I set multi functions to change a single data? I mean, I created a reset function below which has the purpuse to reset the numbers. It is working fine!
Just for an example, I also want to create a function to change the ‘hour’, ‘minute’ and ‘second’ to the value ‘2’.
which is the best way to do it?
It will have two buttons and each button will activate the ‘resetTime’ or ‘changeToTwoTime’.
//data()
const [hour, resetHour] = useState(4)
const [minute, resetMinute] = useState(8)
const [second, resetSecond] = useState(12)
// methods
const resetTime = () => {
resetHour(0)
resetMinute(0)
resetSecond(0)
}
return (
<div className="p-3">
<MainButton
variantButton="outline-success"
textButton="START"
functionButton={resetTime}
/>
<MainButton
variantButton="outline-success"
textButton="START"
functionButton={changeToTwoTime}
/>
</div>
)
>Solution :
Just for an example, I also want to create a function to change the ‘hour’, ‘minute’ and ‘second’ to the value ‘2’.
You don’t need actually to duplicate the function. You could just simply adjust your function so it accepts an argument, which will be the value of the date.
const setTime = (value = 0) => {
resetHour(value);
resetMinute(value);
resetSecond(value);
}
The value argument is optional. If the function is called without any arguments, it will simply reset the times to 0. If value is passed, it will set the timers to that specified value.
<div className="p-3">
<MainButton
variantButton="outline-success"
textButton="START"
functionButton={() => setTime()} // reset timers
/>
<MainButton
variantButton="outline-success"
textButton="START"
functionButton={() => setTime(2)} // set it to 2
/>
</div>