I want to be able to delete elements from my FlatList. I couldn't do it with the onPress of the TouchableOpacity in ItemView so I decided to create a Button with the onPress={botClick} so when I fill the TextInput above that Button it erases that element from the AsyncStorage and then the element is also removed from proddata. My problem is that to see that element removal from the FlatList I have to change my navigation screen to another one and return to see the changes reflected. Can I put something inside of botClick() that refreshes or recharges the screen when the function is called to see the changes automatically without changing screens?
export default function TestScreen () {
const [proddata, setProddata] = useState([]);
const [deletepar, setDeletepar] = useState('');
const whenClick = () => {
console.log("hello");
}
async function botClick(){
try {
await AsyncStorage.removeItem(deletepar);
console.log("Removed");
//Add something here that refreshes or recharges the screen
}
catch(exception) {
}
};
const ItemView = ({item}) => {
return (
<TouchableOpacity onPress={whenClick}>
<View>
<Text>
{item[0]+ ' ' + item[1]}
</Text>
</View>
</TouchableOpacity>
);
};
async function carInState() {
const keys = await AsyncStorage.getAllKeys();
const result = await AsyncStorage.multiGet(keys);
setProddata([...proddata, ...result]);
}
useFocusEffect(
React.useCallback(() => {
carInState();
}, [])
);
return (
<View>
<View>
<TextInput placeholder="..." onChangeText={(val) => setDeletepar(val)}/>
<View>
<Button title="Delete" onPress={botClick}/>
</View>
</View>
<FlatList
data={proddata}
renderItem={ItemView}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
};
It isn't a problem you can manipulate the state directly or get all data againg
async function botClick() {
try {
await AsyncStorage.removeItem(deletepar);
// 1) Variant load data again & invoke setProddata
const keys = await AsyncStorage.getAllKeys();
const result = await AsyncStorage.multiGet(keys);
setProddata([...result]);
// 2) Or you can remove it from you list
setProddata(prevProddata => prevProddata.filter(value => value.x.x.x !== deletepar))
} catch (exception) {}
}