This app developed by react-native. I know that this question can be duplicated but I tried all solution, and they did not work.
I'm very confused. When some item adding/pushing array in object, UI element is updated. But When I delete/splice in same array, this mechanism not working and UI element is not updated. Why?
function createWordsetObject() {
const object = {
name: '',
words: [],
}
return object
}
export default function AddWordScreen({ navigation, route }) {
const [wordsetObject, setWordsetObj] = useState(
route.params == null ? createWordsetObject() : route.params.wordSetObject
)
const [wordsetName, setWordsetName] = useState(
route.params == null ? '' : route.params.wordSetObject.name
)
const [word, setWord] = useState('')
const [meaning, setMeaning] = useState('')
const onPressAddButtonHandler = () => {
if (word != null && meaning != null) {
var addRecord = { word: word, meaning: meaning }
wordsetObject.words.push(addRecord)
setWord('')
setMeaning('')
printLog()
}
}
const onPressDeleteWordButton = index => {
var modifiedObj = wordsetObject
if (modifiedObj.words.length > 0) {
console.log(modifiedObj.words.length)
modifiedObj.words.splice(index, 1)
}
setWordsetObj(modifiedObj)
console.log(wordsetObject.words.length)
}
return (
<ScrollView>
{wordsetObject.words.map((item, index) => {
return (
<ListItem
key={index}
title={item.word}
subtitle={item.meaning}
bottomDivider
rightIcon={
<View style={{ flexDirection: 'row' }}>
<MCIcon name="pencil" size={22} />
<MCIcon
name="delete"
size={22}
color="red"
onPress={() => onPressDeleteWordButton(index)}
/>
</View>
}
/>
)
})}
</ScrollView>
)
}
I would create new object instead of manipulating existing one.
const onPressDeleteWordButton = (index) => {
if(wordsetObject.words.length) {
setWordsetObj(modifiedObj => {
return {
...modifiedObj,
words: modifiedObj.words.filter((pr, ind) => ind !== index)
}
});
}
}