primefaces / primereact

The Most Complete React UI Component Library
https://primereact.org
MIT License
6.9k stars 1.05k forks source link

Dropdown showClear does not trigger a field change in react-hook-form #4603

Closed manuelpoelzl closed 1 year ago

manuelpoelzl commented 1 year ago

Describe the bug

I have a form that is controlled by react-hook-form.

In this form I have a dropdown and a MultiSelect, the availability of the second one depends on the value of the first one, if the first one has nothing selected, the second one is disabled.

Now the first time I select a value in the first dropdown the behaviour is correct, and the availability of the MultiSelect changes. But now when I click on the clear icon of the first dropdown, the dropdown is cleared but no change is detected in the field.

I'm not sure if this is really a bug, because if I specify undefinedas defaultValueeverything works correctly, so that would mean that!getValues("dd1") compares the current value with the default and not whether there is a falsy value behind it like null or undefined.

Reproducer

https://codesandbox.io/s/primereact-test-forked-3vnglm?file=/src/Form1.jsx

PrimeReact version

9.6.0

React version

17.x

Language

TypeScript

Build / Runtime

Create React App (CRA)

Browser(s)

Edge Version 114.0.1823.67

Steps to reproduce the behavior

  1. Open the console in Codesandbox to see the field value changes getting logged
  2. Click the open panel button
  3. See that the second dropdown is disabled
  4. Select something from the first dropdown
  5. Check the console to see that the field value has changed
  6. See that dropdown2 is now enabled
  7. Now clear dropdown1
  8. Dropdown2 stays enabled
  9. Select something from dropdown1
  10. Notice that no field changes are logged anymore

Expected behavior

The field value should be updated correctly.

melloware commented 1 year ago

I think I fixed your Sandbox: https://codesandbox.io/s/primereact-test-forked-z8qrrv

Can you try it. You are right its not a bug. You are starting the default value out as NULL and NULL != undefined. I added a console.log in the onChange and you can see its firing when you press the "X" to set the dropdown back to undefined!

manuelpoelzl commented 1 year ago

Yes, that was the problem, thanks!

melloware commented 1 year ago

My guess is in the guts of React Hook Form its checking against default values or something in their logic and it was not triggering the change.

manuelpoelzl commented 1 year ago

Exactly what I'm thinking now too, since i would have expected the !getValues("dd1") to get triggerd on any kind of falsy value. But the check against the default value seems plausible here