useLocalStorage hook

This commit is contained in:
exromany 2021-08-04 19:32:55 +03:00
parent 65b885c9dd
commit 5dadcd9ee7
5 changed files with 40 additions and 0 deletions

View File

@ -4,6 +4,7 @@ export * from './programIds';
export * as Layout from './layout';
export * from './notifications';
export * from './utils';
export * from './useLocalStorage';
export * from './strings';
export * as shortvec from './shortvec';
export * from './isValidHttpUrl';

View File

@ -0,0 +1,32 @@
type UseStorageReturnValue = {
getItem: (key: string) => string;
setItem: (key: string, value: string) => boolean;
removeItem: (key: string) => void;
};
export const useLocalStorage = (): UseStorageReturnValue => {
const isBrowser: boolean = ((): boolean => typeof window !== 'undefined')();
const getItem = (key: string): string => {
return isBrowser ? window.localStorage[key] : '';
};
const setItem = (key: string, value: string): boolean => {
if (isBrowser) {
window.localStorage.setItem(key, value);
return true;
}
return false;
};
const removeItem = (key: string): void => {
window.localStorage.removeItem(key);
};
return {
getItem,
setItem,
removeItem,
};
};

View File

@ -6,6 +6,7 @@ import { PublicKey } from '@solana/web3.js';
import BN from 'bn.js';
import { WAD, ZERO } from '../constants';
import { TokenInfo } from '@solana/spl-token-registry';
import { useLocalStorage } from './useLocalStorage';
export type KnownTokenMap = Map<string, TokenInfo>;
@ -16,6 +17,7 @@ export const formatPriceNumber = new Intl.NumberFormat('en-US', {
});
export function useLocalStorageState(key: string, defaultState?: string) {
const localStorage = useLocalStorage();
const [state, setState] = useState(() => {
// NOTE: Not sure if this is ok
const storedState = localStorage.getItem(key);
@ -52,6 +54,7 @@ export const findProgramAddress = async (
seeds: (Buffer | Uint8Array)[],
programId: PublicKey,
) => {
const localStorage = useLocalStorage();
const key =
'pda-' +
seeds.reduce((agg, item) => agg + item.toString('hex'), '') +

View File

@ -9,6 +9,7 @@ import {
Metadata,
ParsedAccount,
StringPublicKey,
useLocalStorage,
} from '@oyster/common';
import { WhitelistedCreator } from '@oyster/common/dist/lib/models/metaplex/index';
import { Cache } from 'three';
@ -159,6 +160,7 @@ export const useExtendedArt = (id?: StringPublicKey) => {
const [data, setData] = useState<IMetadataExtension>();
const { ref, inView } = useInView();
const localStorage = useLocalStorage();
const key = pubkeyToString(id);

View File

@ -1,3 +1,4 @@
import { useLocalStorage } from '@oyster/common';
import { TokenInfo } from '@solana/spl-token-registry';
export const LAMPORT_MULTIPLIER = 10 ** 9;
@ -8,6 +9,7 @@ export const filterModalSolTokens = (tokens: TokenInfo[]) => {
};
export async function getAssetCostToStore(files: File[]) {
const localStorage = useLocalStorage();
const totalBytes = files.reduce((sum, f) => (sum += f.size), 0);
console.log('Total bytes', totalBytes);
const txnFeeInWinstons = parseInt(