I have this CheckBox
component that is a simple checkbox button
<CheckBox
className={'w-100'}
checked={isChecked(item.id)}
onClick={() => updateItem(item.id)}
/>
As you can see, it takes two functions isChecked
and updateItem
. Those functions are defined as
const isChecked = useCallback(
(itemId: string) => {
return state.some((id) => id === itemId);
},
[state]
);
const updateItem = useCallback(
(item) => {
setState((myArray) => [...myArray, item]);
console.log(state, item);
},
[setState, state]
);
where const [state, setState] = useState<string[]>([]);
. What I'm trying to achieve is the following: If you click on the checkbox, add that item id inside the array that is kept in the state and mark it as checked. However, console.log(state, item)
prints [], 'item id'
all the time inside this updateItem
as it can't read the state inside it. The same thing goes for isChecked
, state
is empty all the time. However, if I console.log
it somewhere outside of these functions, in the component body, I get an array of item ids. Have any ideas what am I doing wrong because from all the things I can see, it seems that most of the things are set up correctly and I don't know from where this behavior origins. Thanks in advance