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

147
Views
How to pass useState to context actions?

I am having a form where all the functionality is working fine independently, as per design purpose I got a task to have all the form onchanges and save the form functionality into context actions. As that form is used in many places so for common functionality we need to add the code in context actions.

Below is my existing form code snippet where I cannot share complete code:

 const { state, actionsCollection } = useContext(StateContext);
  const [cardholder, setcardholder] = useState(state.creditCard.cardholder);
  const [cardnumber, setcardnumber] = useState(state.creditCard.cardnumber);
 const [errors, setErrors] = useState({
    cardholder: false,
    cardnumber: false
  });
  const onChange = (e) => {
   switch (e.target.name) {
       case "cardholder":
        setcardholder(e.target.value);
        var cardholderName = /^[a-zA-Z\u00C0-\u00FF\s*$]{1,50}$/.test(e.target.value);
        if (e.target.value === "") {
          setcardholder(e.target.value);
        }
        if (cardholderName === true) {
          setcardholder(e.target.value);
          setErrors({ ...errors, cardholder: false });
        }
        break;
........ code continues

}

Here I need to move this onchange code to context action onChangeCreditCardFields():

const onChange = (e) => {
    actionsCollection.booking.onChangeCreditCardFields()
}

onchange is triggering but getting errors as:

setErrors not defined 
setcardholder not defined .....

As I cannot define usestate in actions.

How to migrate my onchange code with this functionality ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The easiest way would be you can add params as state actions into actionsCollection.booking.onChangeCreditCardFields like

const onChange = (e) => {
    actionsCollection.booking.onChangeCreditCardFields(e, setcardholder, setErrors)
}

And then modify your function declaration accordingly

const onChangeCreditCardFields = (e, setcardholder, setErrors) {
   //TODO: Your logic
}
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!