Skip to content

Instantly share code, notes, and snippets.

@rbayuokt
Last active January 4, 2023 10:00
Show Gist options
  • Select an option

  • Save rbayuokt/1c04975f3ad8f4d9c0de061aea25743b to your computer and use it in GitHub Desktop.

Select an option

Save rbayuokt/1c04975f3ad8f4d9c0de061aea25743b to your computer and use it in GitHub Desktop.
AsyncStore utils
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