Last active
January 4, 2023 10:00
-
-
Save rbayuokt/1c04975f3ad8f4d9c0de061aea25743b to your computer and use it in GitHub Desktop.
AsyncStore utils
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import AsyncStorage from '@react-native-async-storage/async-storage'; | |
| interface IDefaultAppStore { | |
| customValue?: boolean; | |
| // your interface | |
| } | |
| const STORAGE_KEY = '@default_app'; | |
| const DEFAULT_APP_STORE: IDefaultAppStore = { | |
| customValue: false, | |
| // your default local store value | |
| }; | |
| // DEFAULT LOCAL STORE KEY | |
| const getAppStore = async (): Promise<IDefaultAppStore> => { | |
| const user = await AsyncStorage.getItem(STORAGE_KEY); | |
| return user !== null ? JSON.parse(user) : DEFAULT_APP_STORE; | |
| }; | |
| const setAppStore = async ( | |
| data: IDefaultAppStore, | |
| ): Promise<IDefaultAppStore> => { | |
| const oldData = await getAppStore(); | |
| const newData = { | |
| ...oldData, | |
| ...data, | |
| }; | |
| await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(newData)); | |
| return newData; | |
| }; | |
| const deleteAppStore = async (): Promise<IDefaultAppStore> => { | |
| const resetUser = DEFAULT_APP_STORE; | |
| await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(resetUser)); | |
| return resetUser; | |
| }; | |
| // DYNAMIC LOCAL STORE KEY | |
| const getItem = <T extends string | boolean>( | |
| key: string, | |
| ): Promise<T | null> => { | |
| const result = AsyncStorage.getItem(key).then(value => { | |
| if (value) { | |
| switch (value.toLocaleLowerCase()) { | |
| case 'true': | |
| return true as T; | |
| case 'false': | |
| return false as T; | |
| default: | |
| return value as T; | |
| } | |
| } | |
| return null; | |
| }); | |
| return result; | |
| }; | |
| const setItem = <T extends string | boolean>( | |
| key: string, | |
| value: T, | |
| ): Promise<void> => { | |
| return AsyncStorage.setItem(key, value.toString()); | |
| }; | |
| const removeItem = (key: string): Promise<void> => { | |
| return AsyncStorage.removeItem(key); | |
| }; | |
| export { | |
| getAppStore, | |
| setAppStore, | |
| deleteAppStore, | |
| getItem, | |
| setItem, | |
| removeItem, | |
| }; | |
| // made with ❤️ by rbayuokt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment