Skip to content

Commit

Permalink
[GEN-1801]: fix bad setState for checkbox (#1884)
Browse files Browse the repository at this point in the history
This pull request includes a simplification of the `Checkbox` component
in the `frontend/webapp/reuseable-components/checkbox/index.tsx` file.
The changes streamline the `useEffect` hook and the `handleToggle`
function.

Key changes:

* Simplified the `useEffect` hook to only set the `isChecked` state
based on the `initialValue` dependency.
* Refactored the `handleToggle` function to directly call `onChange`
with the new value if provided, otherwise update the `isChecked` state.
  • Loading branch information
BenElferink authored Nov 28, 2024
1 parent a2a81e3 commit b75ada3
Showing 1 changed file with 3 additions and 9 deletions.
12 changes: 3 additions & 9 deletions frontend/webapp/reuseable-components/checkbox/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,21 +38,15 @@ const CheckboxWrapper = styled.div<{ $isChecked: boolean; $disabled?: CheckboxPr

const Checkbox: React.FC<CheckboxProps> = ({ title, titleColor, tooltip, initialValue = false, onChange, disabled, style }) => {
const [isChecked, setIsChecked] = useState(initialValue);

useEffect(() => {
if (isChecked !== initialValue) setIsChecked(initialValue);
}, [isChecked, initialValue]);
useEffect(() => setIsChecked(initialValue), [initialValue]);

const handleToggle: React.MouseEventHandler<HTMLDivElement> = (e) => {
if (disabled) return;

e.stopPropagation();

setIsChecked((prev) => {
const newValue = !prev;
if (onChange) onChange(newValue);
return newValue;
});
if (onChange) onChange(!isChecked);
else setIsChecked((prev) => !prev);
};

return (
Expand Down

0 comments on commit b75ada3

Please sign in to comment.