Hi in my application we are using initialstate where the application sample data will be defined and using the context for state management, below is my sample initial state:
-
creditCard: {
isSaved: false,
lastFourDigits: "1235",
loading: false,
cardholder: "",
cardnumber: "",
cardmonth: "",
cardyear: "",
cardcvv: "",
},
etc:{}....
and in my component i am using usestate for setting the data as below :
const { state,actionsCollection } = useContext(StateContext);
const [cardholder, setcardholder] = useState("");
const [cardnumber, setcardnumber] = useState("");
const [cardmonth, setcardmonth] = useState("");
const [cardyear, setcardyear] = useState("");
const [cardcvv, setcardcvv] = useState("");
and in onchange i am setting state as below:
<TextField
name="cardmonth"
label="MM"
error={errors.cardmonth}
value={cardmonth}
onChange={onChange}
onBlur={validateInput}
helperText={errors.cardmonth && "Invalid month"}
className={classes.expiryDateInputs}
/>
onChange=()=>{
let cardMonth = /^0[1-9]|1[0-2]/.test(e.target.value);
if (cardMonth === true) {
setcardmonth(e.target.value.replace(/\D/g, "").slice(0, 2));
setErrors({ ...errors, cardmonth: false });
} else {
setErrors({ ...errors, cardmonth: true });
}
if (state.creditCard.cardyear !== "") {
validateExpiryDate();
}
}
passing states to non related components using below code:
const validateForm = () => {
return actionsCollection.booking.validateForm(
errors,
setErrors,
cardholder,
setcardholder,
cardnumber,
setcardnumber,
cardType,
setCardType,
cardmonth,
setcardmonth,
cardyear,
setcardyear,
cardcvv,
setcardcvv,
isCurrentCaseIncluded,
cardYearValue
);
};
and in actions i am using this code:
const validateForm = (
errors,
setErrors,
cardholder,
setcardholder,
cardnumber,
setcardnumber,
cardType,
setCardType,
cardmonth,
setcardmonth,
cardyear,
setcardyear,
cardcvv,
setcardcvv,
isCurrentCaseIncluded,
cardYearValue
) => {
some validation logic.....
}
Problem is initial state is not updating, I am not getting what is wrong in my code, Anyone please help..