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 })
}
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:
setFormData({...formData, cc_exp_month : cc_exp.split('/')[0] })
setFormData({...formData, cc_exp_year : cc_exp.split('/')[1] })
but that wasnt reliable.
CodePudding user response:
The newly-updated value of formData
cannot be counted on by the second call to setFormData
because the hook is asynchronous. You may want to try calling setFormData()
once with both new values.
setFormData({
...formData,
cc_exp_month: cc_exp.split('/')[0],
cc_exp_year: cc_exp.split('/')[1]
})
CodePudding user response:
When you enqueue multiple updates like
setFormData({...formData, cc_exp_month : cc_exp.split('/')[0] })
setFormData({...formData, cc_exp_year : cc_exp.split('/')[1] })
Each one uses the same un-updated formData
value and overwrites the previous enqueued updates. You should use a functional state update when updating from previous state. You can also combine all the updates into a single update if no individual update update requires previous temp updates. Use array destructuring assignment to create the cc_exp_month
and cc_exp_year
variables and then use object shorthand assignment in the returned state value.
const [cc_exp_month, cc_exp_year] = cc_exp.split('/');
setFormData(formData => ({
...formData, // shallow copy previous state
cc_exp_month, // add new property values
cc_exp_year,
}));