Essentially I have this state object and this method:
const [groupData, setGroupData] = useState({});
// groupData state
groupData = {
group1: [
{ id: 1, name: Mike, age: 24 },
{ id: 2, name: Bob, age: 31 }
],
group2: [
{ id: 3, name: Christin, age: 21 },
{ id: 4, name: Michelle, age: 33 }
],
}
const stateRef = useRef();
stateRef.current = groupData;
const handleRemovePerson = (personToRemoveById: string) => {
const filteredGroupData = Object.fromEntries(
Object.entries(groupData).map(([key, value]) => {
return [key, value.filter((person) => person.id !== personToRemoveById)];
}),
);
setMainContentData(filteredGroupData);
// Now check if group array does not have anymore persons, if empty then delete
group array
console.log('stateRef', stateRef);
// outputs the correct current data
const filteredStateRef = Object.keys(stateRef).map((key) => stateRef[key]);
console.log('filteredStateRef', filteredStateRef);
// outputs previous data ??
};
I tried useRef and once I loop through it, it gives me back the previous data. How can I get the most current data after setting state and then operating on that new data right away? Thank you!
react
version?setMainContentData(filteredGroupData);
used and where is it defined?console.log('stateRef', JSON.stringify(stateRef));
andconsole.log('filteredStateRef', JSON.stringify(filteredStateRef));