BlueWallet/hooks/useOnAppLaunch.ts

71 lines
2.3 KiB
TypeScript
Raw Normal View History

2024-05-31 19:18:01 +02:00
import { useCallback } from 'react';
2024-03-23 00:11:31 +01:00
import AsyncStorage from '@react-native-async-storage/async-storage';
2024-03-23 17:03:18 +01:00
import { TWallet } from '../class/wallets/types';
2024-05-31 19:18:01 +02:00
import { useStorage } from './context/useStorage';
2024-03-23 00:11:31 +01:00
const useOnAppLaunch = () => {
const STORAGE_KEY = 'ONAPP_LAUNCH_SELECTED_DEFAULT_WALLET_KEY';
const { wallets } = useStorage();
2024-03-23 00:11:31 +01:00
2024-03-23 17:33:00 +01:00
const getSelectedDefaultWallet = useCallback(async (): Promise<string | undefined> => {
2024-03-23 17:03:18 +01:00
let selectedWallet: TWallet | undefined;
2024-03-23 00:11:31 +01:00
try {
const selectedWalletID = JSON.parse((await AsyncStorage.getItem(STORAGE_KEY)) || 'null');
2024-03-23 17:03:18 +01:00
if (selectedWalletID !== null) {
selectedWallet = wallets.find((wallet: TWallet) => wallet.getID() === selectedWalletID);
2024-03-23 00:11:31 +01:00
if (!selectedWallet) {
2024-03-23 00:17:38 +01:00
await AsyncStorage.removeItem(STORAGE_KEY);
2024-03-23 17:03:18 +01:00
return undefined;
2024-03-23 00:11:31 +01:00
}
2024-03-23 17:03:18 +01:00
} else {
return undefined;
2024-03-23 00:11:31 +01:00
}
} catch (_e) {
2024-03-23 17:03:18 +01:00
return undefined;
2024-03-23 00:11:31 +01:00
}
2024-03-23 17:33:00 +01:00
return selectedWallet.getID();
2024-03-23 00:17:38 +01:00
// eslint-disable-next-line react-hooks/exhaustive-deps
2024-03-23 17:03:18 +01:00
}, [STORAGE_KEY]);
2024-03-23 00:11:31 +01:00
const setSelectedDefaultWallet = useCallback(
async (value: string): Promise<void> => {
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(value));
},
[STORAGE_KEY],
); // No external dependencies
const isViewAllWalletsEnabled = useCallback(async (): Promise<boolean> => {
try {
const selectedDefaultWallet = await AsyncStorage.getItem(STORAGE_KEY);
return selectedDefaultWallet === '' || selectedDefaultWallet === null;
} catch (_e) {
return true;
}
}, [STORAGE_KEY]); // No external dependencies
const setViewAllWalletsEnabled = useCallback(
async (value: boolean): Promise<void> => {
if (!value) {
const selectedDefaultWallet = await getSelectedDefaultWallet();
if (!selectedDefaultWallet) {
2024-03-23 00:17:38 +01:00
const firstWallet = wallets[0];
2024-03-23 00:11:31 +01:00
await setSelectedDefaultWallet(firstWallet.getID());
}
} else {
await AsyncStorage.setItem(STORAGE_KEY, '');
}
},
2024-03-23 00:17:38 +01:00
// eslint-disable-next-line react-hooks/exhaustive-deps
2024-03-23 00:11:31 +01:00
[STORAGE_KEY, getSelectedDefaultWallet, setSelectedDefaultWallet],
2024-03-23 17:03:18 +01:00
);
2024-03-23 00:11:31 +01:00
return {
isViewAllWalletsEnabled,
setViewAllWalletsEnabled,
getSelectedDefaultWallet,
setSelectedDefaultWallet,
};
};
2024-03-23 17:03:18 +01:00
export default useOnAppLaunch;