For the current project I am working on, I am facing the challenge of retrieving selected items from a Flatlist and passing them to the parent component.
To tackle this issue, I have initialized a local state as follows:
const [myState, setMyState] = useState<IStateType[] | []>([])
Whenever an item is selected, my approach involves adding it to the useEffect block:
useEffect(() => {
const result = myState.filter((el) => el.id !== item.id)
if (isSelected) {
setMyState([
...result,
{
propOne: 0,
propTwo: 1,
id: item.id,
...
},
])
} else {
setMyState(result)
}
}, [isSelected])
However, incorporating myState in the dependency array of the useEffect function is necessary to include each newly selected item. Yet, doing so unfortunately triggers an infinite loop. How can I successfully update my array with the new selections without causing this issue?