Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to add multi functions to the same useState on Reactjs?

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’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading