From 46a578b5cc9c3230448e8d9db0ba6ff75d5b8852 Mon Sep 17 00:00:00 2001 From: Leon Jiang <35908040+leonyjiang@users.noreply.github.com> Date: Mon, 8 Mar 2021 03:20:38 -0500 Subject: Create util for saving recently-searched categories --- src/utils/users.ts | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) (limited to 'src/utils') diff --git a/src/utils/users.ts b/src/utils/users.ts index 653c941e..efae6d20 100644 --- a/src/utils/users.ts +++ b/src/utils/users.ts @@ -19,6 +19,7 @@ import {AppDispatch} from './../store/configureStore'; import {RootState} from './../store/rootReducer'; import { ProfilePreviewType, + CategoryPreviewType, ProfileType, ScreenType, UserType, @@ -196,3 +197,36 @@ export const addUserToRecentlyViewed = async (user: ProfilePreviewType) => { console.log(e); } }; + +/* + * Stores `category` in AsyncStorage as a recently searched category. + */ +export const addCategoryToRecentlySearched = async ( + category: CategoryPreviewType, +) => { + const recentlySearchedCategoriesKey = '@recently_searched_categories'; + let categories: CategoryPreviewType[]; + // retrieve recently-searched categories and set new list + try { + const categoriesJSON = await AsyncStorage.getItem( + recentlySearchedCategoriesKey, + ); + if (categoriesJSON) { + categories = JSON.parse(categoriesJSON); + categories.push(category); + } else { + categories = [category]; + } + // store updated list of recently-searched categories + try { + AsyncStorage.setItem( + recentlySearchedCategoriesKey, + JSON.stringify(categories), + ); + } catch (e) { + console.log(e); + } + } catch (e) { + console.log(e); + } +}; -- cgit v1.2.3-70-g09d2 From 1d4dd2b2e6496374063efe7a4e1f8bde5cab32b1 Mon Sep 17 00:00:00 2001 From: Leon Jiang <35908040+leonyjiang@users.noreply.github.com> Date: Mon, 8 Mar 2021 05:48:09 -0500 Subject: Fix duplicate stores of a category --- src/utils/users.ts | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/utils') diff --git a/src/utils/users.ts b/src/utils/users.ts index efae6d20..15107c99 100644 --- a/src/utils/users.ts +++ b/src/utils/users.ts @@ -213,6 +213,8 @@ export const addCategoryToRecentlySearched = async ( ); if (categoriesJSON) { categories = JSON.parse(categoriesJSON); + // TODO: make this more efficient by comparing shorter key + if (categories.find((c) => c.name === category.name)) return; categories.push(category); } else { categories = [category]; -- cgit v1.2.3-70-g09d2