I've got strings in my storage and I'd like to create a delete button that would delete a key in my storage. My issue is that I'm in a flatList and I can't manage to make it work.
async removeItemValue(key) {
try {
await AsyncStorage.removeItem(key);
return true;
}
catch(exception) {
return false;
}
}
render() {
return (
<View style={styles.container}>
<View>
<FlatList
data={this.state.imgData}
renderItem={({item}) =>
<View style={{flex: 1, alignItems: "center", justifyContent: "center", marginBottom: 20, borderBottomColor:"white", borderBottomWidth:1}}>
<Text>{item.date}</Text>
<Image style={{width: 300, height: 350}} source={{ uri: item.key }} />
<TouchableOpacity style={styles.menuButton} onPress={this.removeItemValue(item.key)}>
<Text>Delete</Text>
</TouchableOpacity>
</View>
}
/>
</View>
</View>
);
} }
Can you please explain to me also why the OnPress method in the touchableOpacity is called when this page is loaded and not only when the button is clicked?
It should work if you define the prop you send in as a (arrow) function:
onPress={() => this.removeItemValue(item.key)}
If you send in the prop like this...
onPress={this.removeItemValue(item.key)}
...then you no longer send in a function, but the value that the function this.removeItemValue(...) returns. The function is executed before passing it in to the component.