Skip to content

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

Open

Description

@Lchasers
/** 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

Activity

  1. U-4-E-A commented on Feb 26, 2024

    @U-4-E-A

    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions