switch to jotai

This commit is contained in:
austinried
2021-06-28 11:12:19 +09:00
parent 17f5639aef
commit 4606586102
13 changed files with 110 additions and 151 deletions

View File

@@ -1,26 +1,28 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
export async function getItem(key: string): Promise<string | null> {
export async function getItem(key: string): Promise<any | null> {
try {
return await AsyncStorage.getItem(key);
const item = await AsyncStorage.getItem(key);
return item ? JSON.parse(item) : null;
} catch (e) {
console.error(`getItem error (key: ${key})`, e);
return null;
}
}
export async function multiGet(keys: string[]): Promise<[string, string | null][]> {
export async function multiGet(keys: string[]): Promise<[string, any | null][]> {
try {
return await AsyncStorage.multiGet(keys);
const items = await AsyncStorage.multiGet(keys);
return items.map(x => [x[0], x[1] ? JSON.parse(x[1]) : null]);
} catch (e) {
console.error(`multiGet error`, e);
return [];
}
}
export async function setItem(key: string, item: string): Promise<void> {
export async function setItem(key: string, item: any): Promise<void> {
try {
await AsyncStorage.setItem(key, item);
await AsyncStorage.setItem(key, JSON.stringify(item));
} catch (e) {
console.error(`setItem error (key: ${key})`, e);
}
@@ -28,7 +30,7 @@ export async function setItem(key: string, item: string): Promise<void> {
export async function multiSet(items: string[][]): Promise<void> {
try {
await AsyncStorage.multiSet(items);
await AsyncStorage.multiSet(items.map(x => [x[0], JSON.stringify(x[1])]));
} catch (e) {
console.error(`multiSet error`, e);
}

View File

@@ -0,0 +1,10 @@
import { atomWithStorage } from 'jotai/utils';
import { getItem, setItem } from './asyncstorage';
export default <T>(key: string, defaultValue: T) => {
return atomWithStorage<T>(key, defaultValue, {
getItem: async () => await getItem(key) || defaultValue,
setItem: setItem,
delayInit: true,
});
}

View File

@@ -1,15 +0,0 @@
import { AppSettings } from '../models/settings';
import { getItem, setItem } from './asyncstorage';
const appSettingsKey = '@appSettings';
export async function getAppSettings(): Promise<AppSettings> {
const item = await getItem(appSettingsKey);
return item ? JSON.parse(item) : {
servers: [],
};
}
export async function setAppSettings(appSettings: AppSettings): Promise<void> {
await setItem(appSettingsKey, JSON.stringify(appSettings));
}