I am trying to update a single object value (boolean) in my array using setState. Based on previous discussions, my approach does not mutate prior state, creates a copy of the original array, updates the copy, and then updates the original array. The 'issue' I have run into is that while the state updates my virtual list, the array does not re-render (FlatList in RN, specifically).
Previous Discussions Referenced: React: how to update state.item[1] in state using setState?
As a work around, I make a copy of my original array and then set the original array to empty. The cost is a very brief 'flicker' whenever the array re-renders.
Question: Is there a better way to update an object's value in my array AND trigger a re-render of the array elsewhere in my application?
Current Solution:
originalArray = [{ id: '123', randomKey: true }, {'234', randomKey: false }, ...]
const index = originalArray.findIndex(item => item.id === currentItemId)
if (index > -1) {
const newArray = [...originalArray]
setOriginalArray([]) // My solution to re-render the array
let updatedItem = {...newArray[index]}
updatedItem.randomKey = !randomKey // the value is a boolean
newArray[index] = updatedItem
setOriginalArray(newArray)
}
Cheers!