I'm trying to keep track of a list of chosen exercises, and then render 'added' if the chosen exercise is in the list, or 'not added' if it's not in the list. I add the exercise to chosenExerciseArray when it's not already included, and remove it if it is. When I use console.log(chosenExerciseArray) it correctly displays the list, but if I use setChosenExercises(chosenExerciseArray) the state does not get updated correctly, and the chosenExerciseArray somehow stops logging the correct array as well.
I've also tried adding chosenExerciseArray as a useEffect dependency, but that causes an infinite loop. I'm really not sure what's going on here, but I believe it's an issue with my understanding of state.
EDIT: The TouchableOpacity is inside of a map, which may also be the issue, but I'm not sure how
<View style={styles.exerciseheadericongroup}>
<TouchableOpacity
onPress={() => {
if(!chosenExerciseArray.includes(exercise.id)) {
chosenExerciseArray.push(exercise.id);
} else {
for(var i=0; i<chosenExerciseArray.length; i++) {
if(chosenExerciseArray[i] === exercise.id) {
chosenExerciseArray.splice(i, 1);
}
}
}
console.log(chosenExerciseArray);
}}
>
{chosenExercises.includes(exercise.id) ? (
<Text>added</Text>
) : (
<Text>not added</Text>
)}
</TouchableOpacity>
</View>