So I try make a form with a conditional checkbox using react hook form but react always give me the previous state of the checkbox value when i save my data in the context. i see some people say you have to add a useEffect cause useState is asynchronous but nothing change for me.
my code:
const ContactFormMain: FunctionComponent<any> = ({ nextFormStep }) => {
const { saveForm, infos } = useContext(ContactFormContext) as ContactFormDataType;
const { register } = useForm({
mode: "onBlur",
})
const [formUserData, setFormUserData] = useState<IContactFormData | {}>(infos[0]);
const [val, setVal] = useState(false)
const [sharingChoice, setSharingChoice] = useState<string>(infos[0].sharePatientInfo)
useEffect(() => {
console.log(sharingChoice)
console.log(val)
}, [sharingChoice, val])
const updateContext = (e: FormEvent<HTMLButtonElement | HTMLTextAreaElement | HTMLInputElement>): void => {
console.log('afterSetState', formUserData);
setFormUserData({
...formUserData,
[e.currentTarget.id]: e.currentTarget.value
})
}
const handleCheck = (e: ChangeEvent<HTMLInputElement>): void => {
console.log(e.target.checked)
setVal(!val)
if(val === true) {
setSharingChoice("Des informations concernant le patient sont transmises dans ce ticket.")
} else {
setSharingChoice("Il n'y pas d'informations patient partagées dans ce ticket.")
}
console.log('checkedValue', val)
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const updateContextWithCheckBox = (e: ChangeEvent<HTMLInputElement> ) => {
handleCheck(e);
updateContext(e);
}
const handleSaveUserInfo = (e: FormEvent, formData: IContactFormData | any) => {
e.preventDefault();
saveForm(formData)
console.log('context', formData)
nextFormStep();
}
return (
<>
<form onSubmit={(e) => handleSaveUserInfo(e, formUserData)}>
<label htmlFor='subjects'>
Raisons
</label>
<div id="subjects">
<button type="button" id="subject" value='Détection de pathologie subtile' onClick={updateContext}> Détection de pathologie subtile </button>
<button type="button" id="subject" value="Gain de temps" onClick={updateContext}> Gain de temps </button>
<button type="button" id="subject" value="impact sur la prise en charge" onClick={updateContext}> impact sur la prise en charge </button>
<textarea {...register("description")} id="description" name="description" defaultValue={infos[0].description} onChange={updateContext} />
<label htmlFor='sharePatientInfo'>
Ne contient pas d'info patient
</label>
<input type="checkbox" placeholder="infoPatient " {...register("sharePatientInfo ")} id="sharePatientInfo" checked={val} value={sharingChoice} name="sharePatientInfo" onChange={updateContextWithCheckBox} />
<button type='submit'>Suivant</button>
</div>
</form>
</>
)
}
export default ContactFormMain;
any idea?