I am new to React and I am very confused about the lifecyle of a functional component. Let's say I have many inputs of type: checkbox, a, b, c and d. Their values are a, b, c and d.
const OnBoarding = () => {
const [isChecked, setIsChecked] = useState({
a: false,
b: false,
c: false,
d: false
});
const [allCheckedItems, setAllCheckedItems] = useState([]);
//Write function that pushes checked value to state array when clicked
const onChecked = e => {
setIsChecked({
...isChecked,
[e.target.value]: e.target.checked
});
const all = Object.keys(isChecked).filter(function(key){
return isChecked[key] === true;
});
console.log("all items that are TRUE : " + all);
setAllCheckedItems([all]);
console.log("allCheckedItems : " + allCheckedItems);
};
useEffect(() => {
console.log(isChecked);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I have a functional component with a state whose type is an object with many properties, all booleans, like so:
const [isChecked, setIsChecked] = useState({
a: false,
b: false,
c: false,
d: false
})
I have an other state that is an array, let's call it allCheckedItems, that is supposed to be an array of all the keys of isChecked set to true.
const [allCheckedItems, setAllCheckedItems] = useState([]);
With a function onChecked, when a checkbox is checked, it's value in the isChecked object sets to true.
I call useEffect() in which I wrote a filter function to filter all properties that are true. All the properties set to true are store in an array called "all".
My problem comes when I have to update the state of the array allCheckedItems. If I write in the useEffect hook:
setAllCheckedItems([all]);
I get an infinite loop. If I write it in my onChecked function, whenever I click on a checkbox, the state of allCheckedItems that I log in the console is LATE of one click. Like, I click to check "a" and it logs:
[]
Then I click on "b" and it logs:
[a]
Then I click on "c" and it logs:
[a, b]
I would like that when I check a box, both states update and that allItemsChecked logs all items checked immediately... Can someone explain to me this behavior? It has given me headaches for days now.