i populated a form with react-hook-form's setValue function (i don't know if it is the best way to set up a form in edit mode).
Once the form was touched from a user, i want (on a button click) to restore the form to the state i've previously setted,
(pay attention that i don't want to reset it but, make it again to the value i've previously setted)
const { register, handleSubmit, watch, reset, errors, setValue } = useForm();
const { id } = useParams()
const { loading, error, data } = useQuery(GET_FBUSER,{
variables: {_id: id},
skip: id === undefined
});
useEffect(() => {
if (data) {
const {_id, id, fbId, name} = data.FBUser[0]
setValue('_id',_id);
setValue('id',id);
setValue('fbId',fbId);
setValue('name',name);
}
}, [data])
<form onSubmit={handleSubmit(onSubmit)}>
<Grid container spacing={3}>
<Grid item xs={4}>
<TextField fullWidth inputRef={register} InputLabelProps={{ shrink: true }} InputProps={{readOnly: true}} name="_id" label="_Id" variant="outlined" />
</Grid>
<Grid item xs={8}>
<TextField fullWidth inputRef={register} InputLabelProps={{ shrink: true }} InputProps={{readOnly: true}} name="id" label="Id" variant="outlined" />
</Grid>
<Grid item xs={12}>
<TextField fullWidth inputRef={register} InputLabelProps={{ shrink: true }} name="name" label="Name" variant="outlined" />
</Grid>
<Grid item xs={12}>
<TextField fullWidth error={errors.fbId} inputRef={register({required : true})} InputLabelProps={{ shrink: true , required: true}} name="fbId" label="Facebook Id" variant="outlined" />
</Grid>
<Grid item xs={12}>
<TextField fullWidth inputRef={register} InputLabelProps={{ shrink: true }} name="note" label="Note" variant="outlined" />
</Grid>
<Grid item xs={12}>
<Button type="submit" variant="contained" color="primary" startIcon={<SaveIcon/>}>Salva</Button>
<Button onClick={reset} variant="contained" color="primary" startIcon={<CancelIcon/>}>Annulla</Button>
</Grid>
</Grid>
</form>
question from:
https://stackoverflow.com/questions/66052811/react-hook-form-undo-the-form-to-previous-state 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…