Home > Software engineering >  React Native - FlatList value not updated when data has changed
React Native - FlatList value not updated when data has changed

Time:12-23

I am using a FlatList which has cards like any social media app. Each card is a sepearte component.And you can add to favourites to every card. When I am updation value for favorites on card the list does not update at all. I got latest array but list shows with older favourites value.

Code for updating favourites on card component

const updatebookMark = () => {
let newArray = [...feedArray];

let id = item.cardId;
const index = newArray.findIndex(object => {
  return object.cardId === id;
});

if (index !== -1) {
  newArray[index].bookmarked = bookmarkSelected;

  addFeedsToLocalDB(newArray);
}
}

Adding to Local DB function

 const addFeedsToLocalDB = async cardsArray => {
await AsyncStorage.removeItem('feedArray');
await AsyncStorage.setItem('feedArray', JSON.stringify(cardsArray));

 setFeedArray([]);
setFeedArray(cardsArray);
 };

Here setFeedArray is state that I am updating using Context API

If I update setFeedArray([]); by making it null and then adding value to it then list updated with the latest value but it cause each time refresh on the list and the list to flickered.

Now Flatlist code:

Get Item from local storage when data changed

useEffect(() => {
getCardsFromLocalDB();

}, [feedArray]);

const getCardsFromLocalDB = async () => {
const feedCards = await AsyncStorage.getItem('feedArray');

if (JSON.parse(feedCards).length > 0) {

  setCount(count   1);
  setFeedCards(feedArray);

  }
 }
 };

And in Flatlist I have used extraData to update value and I used count for that

 <FlatList
        extraData={count}
        data={feedCards}
        scrollEnabled={true}
        renderItem={({item, index}) => (
          <RenderCard
            item={item}
            navigation={navigation}
            index={index}
            managePost={false}
            isPaymentReport={false}
            isBookmark={false}
            previewMode={false}
            isPinnedPost={false}
            isPaymentExplorer={false}
          />
        )}
        numColumns={1}
        keyExtractor={(item, index) => index}
        contentContainerStyle={{
          paddingBottom: height * 0.1,
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: 'transparent',
        }}
        showsVerticalScrollIndicator={false}
        keyboardShouldPersistTaps="handled"
        onEndReachedThreshold={0.05}
        onScrollBeginDrag={() => setLoadingMore(true)}
        onEndReached={handleOnEndReached}
        ListFooterComponent={() => loadingMore && <ListFooterComponent />}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={() => onRefresh()}
            tintColor={Colors.light.black}
          />
        }
      />

Please help

CodePudding user response:

Put your local storage data(feedCards) in the useState and then it will update. Every time you update your state, you can update your local storage, too. In order for component to rerender, state or props need to be changed.

CodePudding user response:

just change this

 const addFeedsToLocalDB = async cardsArray => {
await AsyncStorage.removeItem('feedArray');
await AsyncStorage.setItem('feedArray', JSON.stringify(cardsArray));

 setFeedArray([]);
setFeedArray([...cardsArray]);
 };
  • Related