Leo Messi
Leo Messi

Reputation: 6196

Reset an input field when another one is written in React with react-hook-form

Having the following component:

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

import { Input, TabsGroup, Button } from './ui-components';

import { usePostFrequency } from '../hooks/use-post-frequency';

const schema = yup.object().shape({
  second: yup.number(),
  minute: yup.number(),
  triggerName: yup.string().required()
});

export function FrequencySetter() {
  const [isEditMode, setEditMode] = useToggle(false);
  const emptyTrigger = {
    second: null,
    minute: null,
    triggerName: ''
  };

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

  const handleCancel = () => {
    setEditMode();
    reset(emptyTrigger);
  };

  const handleSubmitClick = handleSubmit((data) => {
    setEditMode();
    postFrequency(data);
  });

  const frequencyTabs = [
    {
      name: 'per second',
      children:
        <div>
          <Input inputId='second' type='number' {...register('second')} />
        </div>

    },
    {
      name: 'per minute',
      children:
        <div>
          <Input inputId='minute' {...register('minute')} />
        </div>

    }
  ];

  return (
    <div>
      <Input inputId='trigger-name' label='triggerName' {...register('triggerName')} />
      <TabsGroup tabs={frequencyTabs} />
      <Button title='cancel' onClick={handleCancel} />
      <Button title='submit' onClick={handleSubmitClick} />
    </div>
  );
}

export default FrequencySetter;

What it has to do:

There is a tab functionality done by an imported component, TabsGroup - which has 2 tabs, it shows the input for seconds on one tab, the input for minutes on the other tab.

The component uses react-hook-form for validation, there are 2 buttons, cancel and submit for obvious reasons.

The problem: the submitted data should contain the triggerName and one of second or minute, NOT both of them. I don't know how to do that - to reset in a way the value of one when I'm introducing data in the input of the other one.

Is there a way to do this?

Upvotes: 4

Views: 7358

Answers (1)

Amila
Amila

Reputation: 3816

You can use watch on the two fields second and minute and use useEffect to setValue of the other field.

export function FrequencySetter() {

  //other code

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

  const second = watch("second");
  const minute = watch("minute");

  useEffect(() => {
    if (!!second) {
      setValue('minute', '')
    }
  }, [second]);

  useEffect(() => {
    if (!!minute) {
      setValue('second', '')
    }
  }, [minute]);

  //other code
}

Upvotes: 3

Related Questions