I have a component on a page that renders a bunch of checkboxes and toggles.
I also have a button called confirm at the bottom to save the changes and make a request to update the back-end.
However I wanted to support a feature that when users haven't made any changes to any of these checkboxes or toggles, the confirm button should be disabled. and when users toggle or check any of these, then the confirm button is enabled and clickable.
so right now what I am doing is
const MyComponent = () => {
const dispatch = useDispatch();
// get the current state from the store
const state = useSelector((state: RootState) => state.settings);
const [isCheckbox1Checked, setCheckbox1] = useState(false);
const [isCheckbox2Checked, setCheckbox2] = useState(false);
const [isCheckbox3Checked, setCheckbox3] = useState(false);
const [isConfirmBtnEnabled, setConfirmBtn] = useState(false);
const [updateBtnEnabled, enableUpdateBtn] = useState(false);
useEffect(() => {
(async () => {
// `getSettingsConfig` is a async thunk action
await dispatch(getSettingsConfig());
setCheckbox1(state.isCheckbox1Checked);
setCheckbox2(state.isCheckbox2Checked);
setCheckbox3(state.isCheckbox3Checked);
})();
}, [
dispatch,
state.isCheckbox1Checked,
state.isCheckbox2Checked,
state.isCheckbox3Checked
// ..
]);
return (
<>
<div className="checkboxes">
<Checkbox1
onCheck={() => {
setCheckbox1(true);
setConfirmBtn(true);
}}
/>
<Checkbox2
onCheck={() => {
setCheckbox2(true);
setConfirmBtn(true);
}}
/>
<Checkbox3
onCheck={() => {
setCheckbox3(true);
setConfirmBtn(true);
}}
/>
</div>
<button disabled={!isConfirmBtnEnabled}>Confirm</button>
</>
);
};
right now it seems to be working out fine but it requires manually spamming setConfirmBtn to every checkbox and toggles I have on this page. I wonder if there is a better way to do it.
Also I thought about using useEffect to call isConfirmBtnEnabled every time any of these state changes. However since the initial state is derived from the store via dispatching an async thunk, the state of these checkboxes and toggles are going to be changed anyways after the page mounts, so that means I cannot use another useEffect to listen on the changes of these state.