Reputation: 121
I am trying to delete an item from my flat list by touching it, but I am unable to do so. I understand that I need to pass the touched index to my deleteMessage()
function, but I'm not sure how to do this.
deleteMessage(item) {
console.log("delete message!");
console.log(item);
index = this.state.messageList.indexOf(item);
console.log(index);
let newList = this.state.messageList.splice(index, 1);
console.log(newList);
this.setState({
messageList: newList
});
}
renderMessage(message) {
console.log(message.item);
return (
<TouchableHighlight onPress={()=> this.deleteMessage()}>
<Text style={styles.message}> {message.item} </Text>
</TouchableHighlight>
);
}
render() {
return (
<View style={styles.container}>
<FlatList
style={styles.listContainer}
data={this.state.messageList}
renderItem={item => this.renderMessage(item)}
/>
<View style={styles.sendContainer}>
<TextInput
style={styles.TextInputStyle}
onChangeText={text => this.handleInputMessage(text)}
placeholder="type message here"
value={this.state.message}
/>
<Button onPress={() => this.handleSubmitMessage()} title="sennd" />
</View>
</View>
);
}
}
Upvotes: 1
Views: 2317
Reputation: 3633
Do it like this:
deleteMessage(item) {
var messageList = [...this.state.messageList]
let index = messageList.indexOf(item);
messageList.splice(index, 1);
this.setState({ messageList });
}
...
is called Spread Operator, in the above code, it copies the this.state.messageList
array. Therefore, when you make any changes to it, you're changing what's in messageList
array instead of this.state.messageList
array
The problems in your code are that:
You are mutating state by calling .splice()
directly on this.state.messageList
.splice()
returns the deleted item(s), not the remaining items, therefore, after you call .splice()
on your state, you new list contains only the items that you had deleted
Have fun!
Upvotes: 3