Skip to content

Commit

Permalink
fix(useSwitch): type guard to fix breaking change we accidentally int…
Browse files Browse the repository at this point in the history
…roduced in previous version (#2330)
  • Loading branch information
YossiSaadi authored Aug 6, 2024
1 parent 780fdf7 commit d07d907
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ describe("useSwitch", () => {
const { result } = renderHookForTest({ defaultChecked: true, onChange });
callOnChange(result);
expect(onChange).toBeCalledTimes(1);
expect(onChange).toBeCalledWith(false, expect.anything());
expect(onChange).toBeCalledWith(false);
});
});

Expand Down
12 changes: 9 additions & 3 deletions packages/core/src/hooks/useSwitch/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ enum SwitchRole {
export interface UseSwitchProps {
isChecked?: boolean;
defaultChecked?: boolean;
onChange?: (value: boolean, event?: ChangeEvent<HTMLInputElement>) => void;
onChange?: (value: boolean, event?: ChangeEvent<HTMLInputElement> | any) => void;
isDisabled?: boolean;
}

Expand All @@ -18,15 +18,21 @@ export default function useSwitch({ isChecked, defaultChecked, onChange, isDisab
const [overrideChecked, setOverrideChecked] = useState(overrideCheckedInitial);

const overrideOnChange = useCallback(
(event?: ChangeEvent<HTMLInputElement>) => {
// TODO fix in next major. We need to remove any type
(event?: ChangeEvent<HTMLInputElement> | any) => {
if (isDisabled) {
return;
}
const newChecked = !overrideChecked;
if (isChecked === undefined) {
setOverrideChecked(newChecked);
}
onChange && onChange(newChecked, event);
// TODO fix in next major. We should always pass the event
if (event && typeof event === "object" && "target" in event) {
onChange?.(newChecked, event);
} else {
onChange?.(newChecked);
}
},
[isChecked, isDisabled, onChange, overrideChecked]
);
Expand Down

0 comments on commit d07d907

Please sign in to comment.