0

I am trying to setState in onChange but as per below code my state is not updating as i am setting this state as i need to use this state values globally in my application, and this states are need to be accessed in actions so i am trying to setstate globally.

my initial state in initialstate.js:

creditCard: {
    isSaved: false,
    lastFourDigits: "1235",
    loading: false,
    cardholder: "",
    cardnumber: "",
    cardmonth: "",
    cardyear: "",
    cardcvv: "",
  }

In mycomponent:

const { state, actionsCollection } = useContext(StateContext);
  const [cardholder, setcardholder] = useState("");
  const [cardnumber, setcardnumber] = useState("");
  const [cardmonth, setcardmonth] = useState("");

const [errors, setErrors] = useState({
    cardholder: false,
    cardnumber: false,
    cardmonth: false,
  });

 const onChange = (e) => {
    e.preventDefault();
    switch (e.target.name) {
      case "cardnumber":
        let value = e.target.value.replace(/\D/g, "");
        setcardnumber(value);
        let cardTypeSelected;
        const regexPattern = {
          MASTERCARD: /^5[1-5][0-9]{1,}|^2[2-7][0-9]{1,}$/,
          VISA: /^4[0-9]{2,}$/,
          AMERICAN_EXPRESS: /^3[47][0-9]{5,}$/,
          DISCOVER: /^6(?:011|5[0-9]{2})[0-9]{3,}$/,
          DINERS_CLUB: /^3(?:0[0-5]|[68][0-9])[0-9]{4,}$/,
          JCB: /^(?:2131|1800|35[0-9]{3})[0-9]{3,}$/,
        };
        for (const card in regexPattern) {
          if (value.replace(/[^\d]/g, "").match(regexPattern[card])) cardTypeSelected = card;
        }

        setCardType(cardTypeSelected);
        let res;
        if (cardType) {
          if (cardType === "AMERICAN_EXPRESS") {
            res = `${value.slice(0, 4)} ${value.slice(4, 10)} ${value.slice(10, 15)}`;
            if (res.length < 17) {
              setErrors({ ...errors, cardnumber: true });
            } else {
              setErrors({ ...errors, cardnumber: false });
            }
          } else {
            res = `${value.slice(0, 4)} ${value.slice(4, 8)} ${value.slice(8, 12)} ${value.slice(12, 16)}`;
            setErrors({ ...errors, cardnumber: true });
          }
        } else {
          res = `${value.slice(0, 4)} ${value.slice(4, 8)} ${value.slice(8, 12)} ${value.slice(12, 16)}`;
          setErrors({ ...errors, cardnumber: true });
        }
        var cardNoFormatted = res.trim();
        setcardnumber(cardNoFormatted);
        break;
      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);
          //state.creditCard.cardholder = e.target.value;
          setErrors({ ...errors, cardholder: false });
        }
        break;
      case "cardmonth":
        setcardmonth(e.target.value.replace(/\D/g, "").slice(0, 2));
break;
 default:
        break;
    }
  };

in return:

 <TextField
                name="cardholder"
                label="Card holder"
                error={errors.cardholder}
                value={cardholder}
                onChange={onChange}
                helperText={errors.cardholder && "Invalid card holder"}
                className={classes.cardHolderNumberInputs}
              />
              <TextField
                name="cardnumber"
                label="Card number"
                error={errors.cardnumber}
                value={cardnumber}
                onChange={onChange}
                helperText={errors.cardnumber && "Invalid card number"}
                className={classes.cardHolderNumberInputs}
              />
  <TextField
                    name="cardmonth"
                    label="MM"
                    error={errors.cardmonth}
                    value={cardmonth}
                    onChange={onChange}
                    onBlur={validateInput}
                    helperText={errors.cardmonth && "Invalid month"}
                    className={classes.expiryDateInputs}
                  />

Any help please as i am not able to see the state updated,is the above code right or do i need to do any changes in my code.

Sudhir
  • 1
  • 1
  • 9
  • 24
  • Which state is not getting updated? Also, who do you mean _globally_? `useState` is only at component level not application... – Suraj Rao Jun 13 '22 at 04:41
  • @SurajRao i am having initialstate where intitial values are defined, I am trying to set values on change in my component and will use the same initial state with updated values in other component where the values will be submitted – Sudhir Jun 13 '22 at 04:45
  • You either need to send by props or use context. Depends on how these components are set. useState is at that component level – Suraj Rao Jun 13 '22 at 04:47
  • in this application we are using context – Sudhir Jun 13 '22 at 04:48
  • 2
    If your values are set in context, you need to use [Context API](https://reactjs.org/docs/context.html#updating-context-from-a-nested-component) to update them...not `useState`. – Suraj Rao Jun 13 '22 at 04:52
  • @SurajRao in applicatioin we are already using context api , can you please give the answer below how to achieve that – Sudhir Jun 13 '22 at 05:00

0 Answers0