Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

about useMergedState(null,{...}) #227

Open
Lchasers opened this issue Feb 1, 2023 · 1 comment
Open

about useMergedState(null,{...}) #227

Lchasers opened this issue Feb 1, 2023 · 1 comment

Comments

@Lchasers
Copy link

Lchasers commented Feb 1, 2023

/** We only think `undefined` is empty */
function hasValue(value: any) {
  return value !== undefined;
}

I think using useMergedState is unreasonable

<Checkbox checked={null} defaultChecked={true} onChange={onChange}>
    Checkbox
</Checkbox>
{/* Correct */}
<input type="checkbox" checked={null} defaultChecked />

Show different results

@U-4-E-A
Copy link

U-4-E-A commented Feb 26, 2024

I ended up creating my own checkbox by copying this repo and modifying it to fit my needs.

One of the issues I had was with including useMergedState in my module.... this seems to be an export issue with the rc-util package not being developed for ESM.

My solution was to get rid of useMergedState entirely. The alternative was actually quite simple - useEffect and useState combined: -

const [isChecked, setIsChecked] = useState<boolean>(false)

  useEffect(() => {
    setIsChecked(checked || defaultChecked || false)
  }, [setIsChecked, checked, defaultChecked])
  const handleChange = (e: ChangeEvent<HTMLInputElement>): void => {
    if (disabled) return
    setIsChecked(!isChecked)
    [...]
  }

Then I can just use the state isChecked as normal (where rawValue would have been used).

I created a test harness of all possibilities and it passed: -

const arr = [
  { checked: undefined, defaultChecked: undefined, expected: false },
  { checked: undefined, defaultChecked: false, expected: false },
  { checked: undefined, defaultChecked: true, expected: true },
  { checked: false, defaultChecked: undefined, expected: false },
  { checked: false, defaultChecked: false, expected: false },
  { checked: false, defaultChecked: true, expected: true },
  { checked: true, defaultChecked: undefined, expected: true },
  { checked: true, defaultChecked: false, expected: true },
  { checked: true, defaultChecked: true, expected: true }
]

All elements displayed and behaved as expected.

Although I am considering moving the defaultChecked option to force this to be a controlled component (personal preference).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants