0

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:

enter image description here

Andpej
  • 99
  • 3
  • 13
  • I tried a different approach in my updateBookShelf function by removing the item from the state before I delete it from AsyncStorage, and by doing it this way I don´t have to switch tabs for the FlatList to re-render, however it doesn't re-render at once. It takes several seconds before the items disappears.. – Andpej Jul 21 '18 at 18:39
  • ..but it disappears directly when I pull to refresh on the list or press the Book Shelf tab. – Andpej Jul 21 '18 at 18:50
  • I think the problem is in your getData function. getItem returns a promise but you are trying to assign it to books. Either change that function to be an async function or directly return from inside of the promise like .then(books => (return JSON.parse(books))) – Ismail Hakki Tekin Jul 21 '18 at 18:55

0 Answers0