I have many checkboxes, and use them to set table columns.
It’s look like
const [fields, setFields] = useState<Set<string>>(new Set(["name"]));
const handleChangeFilter = (event: ChangeEvent<HTMLInputElement>) => {
if (fields.has(event.target.value)) {
fields.delete(event.target.value)
} else {
fields.add(event.target.value)
}
setFields(fields)
};
{filters.map((field) => {
return (<FormControlLabel control={<Checkbox onChange={(event) => {
handleChangeFilter(event) }} value={field} checked={fields.has(field)} />} label={ field } />)
})}
and fields changes as expected but checkboxs doesn’t work.
I click and field add in fields but checkbox dosn’t change.
Am I need state control for every field, but there’re to many. I don’t try to use Map in useState is it good idea?
2
Answers
The issue with your checkbox not updating is that Set is a mutable object, and React doesn’t detect changes in its state when you modify it directly. To solve this, you should create a new Set and update the state with this new Set.
Set is mutable that means when there is any change in the set, it will not re-render the page. So you have to create new set from the existing set after adding and deleting.