I am building an app using React hooks.
but the problem is I can intentionally click the button twice to occurs an error.
So I want to disabled the button while I send api request using useState when I clicked the button.
However sending api and useState both work asynchrously, it might hard to expect how it works.
Therefore I have come up with an idea of using callback function of setState in React but since I am new to React hooks, it is hard to grasp of idea how to use setState callback function in React hooks.
Here is the code:
const submitForm = (values: IAgreeMentValues) => {
const userActivate = Object.assign(props.currentUserObject, values, {c})
delete userActivate.email
const userActivateJSON = JSON.stringify(userActivate)
if(values.is14YearsOldOrOlder && values.isAcceptedPrivacyPolicy && values.isAcceptedTerm) {
setButtonState(true)
activateUser(userActivateJSON).then(response => {
if(response.data.result.canLogin) {
popupStore.add({
type: 'alert',
title: t('signUp.agreeMent.registeredCompleted'),
actionString: t('popUpAlert.ok'),
onSubmit: isMobile ? pushToAppStore : pushToLogin
})
} else {
popupStore.add({
type: 'alert',
title: t('error.occured'),
actionString: t('popUpAlert.ok')
})
}
})
.catch(response => {
setButtonState(false)
popupStore.add({
type: 'alert',
title: response.response.data.error.message,
actionString: t('popUpAlert.ok'),
})
})
} else {
popupStore.add({
type: 'alert',
title: t('signUp.agreeMent.mustBeChecked'),
actionString: t('popUpAlert.ok')
})
}
};
return (
<>
<div className='signup-step-wrap'>
<div className='agree-check-box'>
<Formik enableReinitialize={true} initialValues={termsAllSelected}
onSubmit={ (values) => submitForm(values)}>
{({ values, handleChange, handleSubmit }) => (
<form onSubmit={handleSubmit}>
<ul className='check'>
<li>
<Field type='checkbox' name={`isAcceptedMarketingEmail`} id={`agree4`} onChange={handleChange} />
<label htmlFor={`agree4`}>{t('signUp.agreeMent.isAcceptedMarketingEmail')}</label>
</li>
<li>
<Field type='checkbox' name={`isAcceptedMarketingSms`} id={`agree5`} onChange={handleChange} />
<label htmlFor={`agree5`}>{t('signUp.agreeMent.isAcceptedMarketingSms')}</label>
</li>
</ul>
<div className='btn-btm-signin'>
<button className='btn-signin active' type='submit' disabled={currentButtonState} style={currentButtonState ? {background: '#e2e2e2'}:{background: '#1f1f1f'}}>{t('signUp.agreeMent.next')}</button>
</div>
</form>
)}
</Formik>
</div>
</div>
</>
)
const [currentButtonState, setButtonState] = React.useState(false);
. Here's an example codesandbox.io/s/objective-flower-c1bh7 – sanjsanj