So I need to split a credit card expiration date into two separates values in my formData.
Here is how I have the component setup.
const [ formData, setFormData ] = useState({
email: '',
password: '',
username: '',
card_num: '',
cvv_code: '',
cc_exp: '',
cc_exp_year: '',
cc_exp_month,
first_name: '',
last_name: '',
})
I also desctructure all the formData here:
const { email, password, username, card_num, cvv_code, cc_exp, cc_exp_year, cc_exp_month, first_name, last_name } = formData;
I have my onChange function here:
const onChange = e => {
setFormData({ ...formData, [e.target.name]: e.target.value })
}
a
and when I type in the expiration date for cc_exp I get the correct format of MM/YY but I need to split the value into cc_exp_month and cc_exp_year. So my question is, where is the best place to split the string at the / and then how can I add them to the those values in formData.
I have tried setFormData in the onSubmit function to just add the values after the fact with a simple:
const onSubmit = e => {
e.preventDefault();
setFormData(formData => ({
...formData, // shallow copy previous state
cc_exp_month: cc_exp.split('/')[0], // add new property values
cc_exp_year: cc_exp.split('/')[1],
username: email
}));
dispatch(createMembership(formData, id));
}
I thought that the best place to do this would be onSubmit before I sent the data anyway. Just so I wouldn't have to chain functions together and because I really just wasnt sure where to add it. So After cc_exp is set and all the form data is there I am trying to split that value and then apply it to these other values cc_exp_month & cc_exp_year before I submitted the data. But when I click onSubmit the month and year dont show. But if I was to click the submit twice (which no one would ever do) then the data shows up correctly in formData. So its like setFormData doesnt want to add the new exp data for some reason in onSubmit.