I have this component
const CheckboxColumn: FC<ICheckboxColumnProps> = ({ id_llamada }) => {
// select pickup
const dispatch = useTypedDispatch();
const [isPickupSelected, setIsPickupSelected] = useState(false);
const selectPickup = (e: ChangeEvent<HTMLInputElement>) => {
setIsPickupSelected(e.target.checked);
dispatch(controlPickup(id_llamada));
};
return (
<TableCell
component={'div'}
padding="checkbox"
sx={{ padding: '0px 0px 0px 4px' }}
onClick={(e) => {
e.stopPropagation();
}}
>
<Checkbox
color="primary"
checked={isPickupSelected ? true : false}
// disabled={true}
sx={{
padding: '7px',
'&:hover': {
backgroundColor: 'rgba(0, 0, 0, 0.06)',
},
}}
onChange={selectPickup}
/>
</TableCell>
);
};
export default CheckboxColumn;
And I need to be able to select a table's row, but also dispatch its information to redux, the problem, is that, I can't figure out how to use setState
along with dispatch
.
What is currently happening is that my isPickupSelected
is not updating its value, but data it's actually being saved in my reducer, and, when I comment the dispatch(function())
my state is being able to work properly.
I've been trying to search solutions to this, and one of them was that, I should use useEffect
and whenever my state changes, I should dispatch the function, and it works, but immediately, it literally restarts my component, and also my isPickupSelected
so my state is no longer updated but returns to its original value of false
.
What am I supposed to do in this case?
You shouldn't have to make the equality check below since isPickupSelected
is already a boolean
value.
checked={isPickupSelected ? true : false}
Try simply using:
<Checkbox
color="primary"
checked={isPickupSelected}
...
Also, given that the checkbox can only be checked or unchecked, you actually could do:
const selectPickup = () => {
setIsPickupSelected(!isPickupSelected) // instead of `e.target.checked`
This way, when the user clicks on the checkbox, the state setter will set isPickupValue
to the opposite of whatever the current value is (toggling).
Let me know if that fixes your issues? Cheers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With