react-admin icon indicating copy to clipboard operation
react-admin copied to clipboard

Unmounting inputs doesn't reset/clear them.

Open whoiskonstantin opened this issue 3 years ago • 3 comments

What you were expecting:

Expect field inputs to be unmounted and the input value to be reset/clear with this code:

<FormDataConsumer>
    {({ formData, ...rest }) => formData.hasEmail &&
        <TextInput source="email" {...rest} />
    }
</FormDataConsumer>

What happened instead: Form values are persisted and submitted with the form.

Steps to reproduce: You can copy paste the form from the official documentation and test it.

React admin v4.3.1

whoiskonstantin avatar Sep 20 '22 00:09 whoiskonstantin

I suggest watching for changes to the field you want and resetting the field manually.

    import {useFormContext} from "react-hook-form";
    ...

    const {watch, resetField} = useFormContext();
    const inputValue = watch("hasEmail");

    useEffect(() => {
        if (!inputValue) resetField("email");
    }, [inputValue]);

KonkretneKosteczki avatar Sep 20 '22 12:09 KonkretneKosteczki

@KonkretneKosteczki Thank you! Worked with unregister in my case, but reset works too. Closing.

whoiskonstantin avatar Sep 20 '22 16:09 whoiskonstantin

This behavior is the responsibility of react-hook-form. You can solve it by passing shouldUnregister in your Form.

<SimpleForm shouldUnregister>
     <BooleanInput source="hasEmail" />
     <FormDataConsumer>
         {({ formData, ...rest }) => formData.hasEmail &&
              <TextInput source="email" {...rest} />
         }
     </FormDataConsumer>
</SimpleForm>

@fzaninotto, Plus, maybe we should add this to the docs. And maybe consider setting shouldUnregister=true as default value for react-admin Forms.

WiXSL avatar Sep 21 '22 18:09 WiXSL