I´m creating an app where I want to add books to a book shelf. Right now the app contains two tabs, BookShelf which shows a flatlist of all the books added, and AddBook which right now contains two buttons to add some dummy data to test the functionality.
The books are stored as objects in an array in AsyncStorage and I´m updating the state of my BookShelf component by fetching the data stored in AsyncStorage. Adding books to the flatlist works fine but I´m having some problems with the UI of the flatlist not updating properly when a item is removed from the list. Right now I have to switch to the AddBook tab and back to BookShelf to trigger a re-render of the flatlist with the selected item removed. Any ideas how to solve this and make the flatlist re-render directly when I press the delete button?
These are my functions for adding, fetching, and deleting data in AsyncStorage:
export function addData(book) {
AsyncStorage.getItem('@books')
.then((books) => {
let b = books ? JSON.parse(books) : [];
b.push(book);
AsyncStorage.setItem('@books', JSON.stringify(b));
});
}
export function getData() {
let books = AsyncStorage.getItem('@books')
.then(books => (JSON.parse(books)))
return books;
}
export function removeData(id) {
AsyncStorage.getItem('@books')
.then((books) => {
let allBooks = JSON.parse(books)
let filteredBooks = allBooks.filter(item => item.id != id);
AsyncStorage.setItem('@books', JSON.stringify(filteredBooks));
})
}
And this is my function in the BookShelf component when delete is pressed on an item in the flatlist:
updateBookShelf = (id) => {
removeData(id), () => {
getData().then((data) => {
this.setState({
books: data
})
})}
Here is a GIF that illustrates how the app behaves when I try to remove an item: