useWatch
useWatch
returns a React state for the values of the field being watched.
Parameters
useWatch
takes an optional parameter representing the name of the fields to watch:
- it can be a string for a single field
- it can be an array a string for multiple fields
- if nothing is passed then all fields are watched
Returns
useWatch
returns the values as React state.
Usage
0
import { type FormEvent } from 'react';
import type { IProps } from '../types';
import {
FormProvider,
type IFormValues,
useForm,
useFormErrors,
useWatch,
} from '@per-form/react';
function Input() {
const errors = useFormErrors();
const { text } = useWatch<{ text: string }>('text');
return (
<>
<input name="text" required />
{errors.all.text && <div className="error">{errors.all.text}</div>}
<div>value = {text}</div>
</>
);
}
export default function Demo(props: IProps) {
function handleSubmit(_e: FormEvent<HTMLFormElement>, values: IFormValues) {
console.log(values);
}
const { formProps, ...context } = useForm({
...props,
onSubmit: handleSubmit,
});
return (
<FormProvider {...context}>
<form {...formProps}>
<Input />
<div className="actions">
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</div>
</form>
</FormProvider>
);
}