I have an array of objects, and each object has a false property value by default:
const [items, setItems] = useState([ { key: 1, has_x: false }, { key: 2, has_x: false }, { key: 3, has_x: false } ]);
Which is passed down to child components:
<Item key={item.key} hasX={item.has_x} />
In the parent component, I have a "Check All" button:
<button onClick={handleCheckAll}>Check All</button>
Which would loop through every item and modify item.has_x to true.
In the child components, there's also a "Check" button, but instead of checking all items, it just checks and sets that one specific item has_x to true.
I think I would know how to do each one. For the "Check All" function, I'd create a shadow copy, set the value, and then once the loop is done, set the state. For the child button, I really just need a useState there for it.
However, I am stuck on the "Check All" button because I'd like to have ui updates as has_x for each item gets updated and a setTimeout, as the actual functionality of check all will be expensive and needs about 200-300ms wait time for each check. Imagine a button's text changes to a checkmark as the function loops through each item.
Here's my attempt but the UI doesn't get updated and I only am setting the state once it's done:
const checkAllItems = () => {
let temp = [...items];
temp.map((item, index) => {
setTimeout(() => {
let tempEl = {...tempState[index]};
if (tempEl) item.has_x = true;
}, index * 200)
})
setItems(temp)
}
My only idea of how to do this is to use refs and loop through the refs to run a function in each child component that will do this, but I feel like there's a correct way to go about this. How is it possible?