Issue
My goal is to define a state that holds an array of selected ID's i.e.
const [selectedIds, setSelectedIds] = useState([])
in a 'grandparent' component that can get updated when changes are made within a grandchild component. That way, I can then use this updated data in another component (we'll say 'uncle' component) that is a child of grandparent.
I'm new to React, so I'm not sure if this is the 'proper' way to handle a scenario like this, and I can't figure out why my state is getting set (potentially re-initialized) to = 1 between selecting checkboxes (any insight into general causes for this would be helpful).
Here's an outline of what I'm attempting to do: Grandparent component:
const GrandParent = (props) => {
const [selectedIds, setSelectedIds] = useState([]);
const updateStateUsingDataFromGrandchild = (id) => {
setSelectedIds(selectedIds.push(id));
}
return(
<div>
<Parent updateStateUsingDataFromGrandchild={updateStateUsingDataFromGrandchild}></Parent>
<Uncle selectedIds={selectedIds}></Uncle> //my overall goal is to get updated selectedIds passed to here
</div>
);
}
Parent Component (just passing the function through this)
const Parent = (props) => {
return(
<div>
<GrandChild updateStateUsingDataFromGrandchild={updateStateUsingDataFromGrandchild}></GrandChild>
</div>
);
}
GrandChild - When a checkbox is checked, call the function in the grandparent, passing the id
const GrandChild = (props) => {
const handleCheckedInput = (event) => {
props.updateStateUsingDataFromGrandchild(event.target.id);
}
return(
<div>
<input onChange={handleCheckedInput} type="checkbox" id="1" /> Thing1
<input onChange={handleCheckedInput} type="checkbox" id="2" /> Thing2
</div>
);
}
What I see while debugging: in first checkbox check, updateStateUsingDataFromGrandchild() is called with the id passed, and updates selectedIds in the grandParent component. However, by the time I click the second checkbox and enter the function in the grandparent, selectedIds evaluates to = 1, and has seemingly been re-initialized or something? I would expect selectedIds to contain the id I had already pushed to it.
Solution
push
returns the new length of the array, so when you do this:
setSelectedIds(selectedIds.push(id))
you’re setting selectedIds
to the new length of the array. You could do this instead:
setSelectedIds([…selectedIds, id])
Answered By - ray
Answer Checked By - - Willingham (ReactFix Volunteer)