FairyQueen
FairyQueen

Reputation: 2373

How to filter out items that were not previously added to an array in React Native?

Whenever a user does a product search in our app we need to cache the search results in local storage so that when they are offline and they perform a search it can pull up previously searched items. With each new search we need to only add the new items to the searchCache. So if they search for 'be' first then search for 'b' there will be overlapping results but we don't want to add items that are already stored. This is currently not working though because it still returns all of the items in the search instead of filtering them. Does anyone know how to achieve this?

I want to filter the searchResults by their ids. Comparing ids to return the items that have ids that are not already in the searchCache.

newItems = searchResults.filter((searchResult) => {
    return searchCache.find(searchCacheItem => searchCacheItem.id !== searchResult.id);
});

Here is the entire action function:

export function handleProductSearch(searchTerm) {
    return (dispatch, getState) => {
        return dispatch(getProductList(searchTerm)).then((results) => {
            const searchResults = results.items;

            // Get previously stored product search cache
            AsyncStorage.getItem(STORAGE_KEY_PRODUCT_SEARCH_CACHE).then((results) => {
                return JSON.parse(results);
            }).then((response) => {
                const searchCache = response || [];
                let newItems = [];

                if (searchCache.length > 0) {
                    // Check for duplicates in the recently added items.  Only add the items that are new and not already in the searchCache.
                    newItems = searchResults.filter((searchResult) => {
                        return searchCache.find(searchCacheItem => searchCacheItem.id !== searchResult.id);
                    });
                }

                searchCache.push(newItems.length > 0 ? newItems : searchResults);
                AsyncStorage.setItem(STORAGE_KEY_PRODUCT_SEARCH_CACHE, JSON.stringify(searchCache));
            }).catch(err => {
                console.log('Error retrieving product search cache: ', err);
            });
        });
    };
}

Upvotes: 0

Views: 81

Answers (1)

bennygenel
bennygenel

Reputation: 24660

You should first check if the item is already exists and then if not push it to the array.

Sample

let newItems = [];

if (searchCache.length > 0) {
  // Check for duplicates in the recently added items.  Only add the items that are new and not already in the searchCache.
  searchResults.forEach(searchResultItem => {
    if(!searchCache.find(searchCacheItem => searchCacheItem.id === searchResultItem.id)) newItems.push(item)
  });
}

Upvotes: 1

Related Questions