ghost-portal/packages/react-hooks/src/useFavorites.ts
2020-09-17 16:46:46 +02:00

26 lines
835 B
TypeScript

// Copyright 2017-2020 @polkadot/react-hooks authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { useCallback, useState } from 'react';
import useCacheKey from './useCacheKey';
// hook for favorites with local storage
export default function useFavorites (storageKeyBase: string): [string[], (address: string) => void] {
const [getCache, setCache] = useCacheKey<string[]>(storageKeyBase);
const [favorites, setFavorites] = useState<string[]>(getCache() || []);
const toggleFavorite = useCallback(
(address: string): void => setFavorites(
(favorites: string[]) => setCache(
favorites.includes(address)
? favorites.filter((accountId): boolean => address !== accountId)
: [...favorites, address]
)
),
[setCache]
);
return [favorites, toggleFavorite];
}