Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset values from react-hook-form when the form is closed

Having the following component:

import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from 'react-hook-form';
import * as yup from 'yup';

import { useToggle } from '../shared/hooks';
import {
  SubsectionLayout,
  Footer,
  Textarea,
  Input,
  Modal,
  Button
} from '../shared/ui-components';

const schema = yup.object().shape({
  name: yup.string().required(),
  description: yup.string().required()
});

export interface ITask {
  name: string;
  description: string;
}

export function MainComponent() {
  const [isOpened, toggleModal] = useToggle(false);

  const { handleSubmit, register, reset } = useForm({
    resolver: yupResolver(schema)
  });

  const onSubmit = (data: ITask) => {
    console.log('data: ', data);
    toggleModal();
    reset(data);
  };

  return (
    <div>
      <Button onClick={toggleModal} />
      <SubsectionLayout title='test'>
        <Modal
          title='add element'
          open={isOpened}
          onClose={toggleModal}
          footer={
            <Footer onSubmit={handleSubmit(onSubmit)} onCancel={toggleModal} editMode={true} />
          }
        >
          <div>
            <Input
              inputId='calculation-engine-script-name'
              label='name'
              {...register('name')}
            />

            <Textarea label='description' {...register('description')} />
          </div>
        </Modal>
      </SubsectionLayout>
    </div>
  );
}
export default MainComponent;

It has a button, when clicked it opens a modal where a user can write inside name and description fields.

When the submit button is clicked it must log the content (for testing purpose) and close the modal.

The problem is that when I open again the modal, the input that was introduced before is still there.

I added reset(data) inside onSubmit() but it doesn't seem to be enough.

Any ideas?

like image 260
Leo Messi Avatar asked Jan 24 '26 08:01

Leo Messi


1 Answers

Try reset({ name: '', description: '' });

like image 173
Shakya Karunathilake Avatar answered Jan 26 '26 23:01

Shakya Karunathilake



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!