Reputation: 1783
I am trying to remove the data from a FlatList that it renders the sales from a JSON file data.json
The problem is that when I remove the sale with a certain id and I go back to home page, it shows all the items again. So how can I remove the items from the source and the items will be removed for the whole life of the application until the user closes and reopens again?
Any help would be very much appreciated.
import data from './data.json';
{
"sales": [
{
"id": 1,
"amount": 100
},
{
"id": 2,
"amount": 200
},
]
}
state = {
data: data.sales
}
onPressRemove(id) {
this.setState(
prevState => {
let data = prevState.data.slice();
let newId = 0;
for (var i=0; i < data.length; i++){
if (data[i].id === id){
newId = i;
}
}
data.splice(newId, 1)
return { data };
});
}
Upvotes: 1
Views: 61
Reputation: 538
beside from using redux, alternatively you can update your data.json programatically using fs , but since it become more difficult i recommend to try redux
Upvotes: 0
Reputation: 9769
After operation update your state again
onPressRemove(id) {
const { data } = this.state;
let filteredData = data.filter(d=> d.id!==id);
this.setState({data:filteredData});
}
Upvotes: 1
Reputation: 2440
The problem right here is that where you go to another part of your app this component will UNMOUNT and when you go back to this component he will mount and use the state from the import (data.json). For this kind of problem, many people choose to go with redux.
Another way would be to keep the state on the parent and give it as a prop to this component, so even when that will unmount and mount again it will still have the prop unchanged (because parent never unmounts).
If you have more questions in implementation, feel free to comment/share your code if you stuck implementing my answer.
Upvotes: 1