From 047944d08c34ae2eeb518f8112ec62c96da3bc3c Mon Sep 17 00:00:00 2001 From: Pierre Bertet Date: Wed, 5 May 2021 16:27:13 +0100 Subject: [PATCH] Cache NFT data between mounts (#59) --- src/core.tsx | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/src/core.tsx b/src/core.tsx index dae9b87..9a61039 100644 --- a/src/core.tsx +++ b/src/core.tsx @@ -16,7 +16,7 @@ import type { EthersFetcherConfig } from "./fetchers/ethers/types" import type { EthereumFetcherConfig } from "./fetchers/ethereum/types" import React, { createContext, useCallback, useContext, useMemo } from "react" -import useSWR from "swr" +import useSWR, { SWRConfig, createCache } from "swr" import ethersFetcher from "./fetchers/ethers" import ethereumFetcher from "./fetchers/ethereum" @@ -67,16 +67,27 @@ function normalizeFetcher(fetcher: FetcherProp): Fetcher { const NftContext = createContext<{ fetcher?: Fetcher | null + cacheStorage: Map } | null>(null) const NftProvider: FC<{ children: ReactNode fetcher?: Fetcher | FetcherDeclaration | null }> = function NftProvider({ children, fetcher }) { + const [cacheStorage, { cache: swrCache }] = useMemo(() => { + const cache = new Map() + return [cache, createCache(cache)] + }, []) + + const contextValue = { + cacheStorage, + fetcher: normalizeFetcher(fetcher), + } + return ( - - {children} - + + {children} + ) } @@ -86,7 +97,7 @@ function useNft(contractAddress: Address, tokenId: string): NftResult { throw new Error("Please wrap your app with ") } - const { fetcher } = context + const { fetcher, cacheStorage } = context const fetchNft = useCallback(() => { return fetcher @@ -94,10 +105,16 @@ function useNft(contractAddress: Address, tokenId: string): NftResult { : { ...NFT_METADATA_DEFAULT } }, [contractAddress, fetcher, tokenId]) + const cached = cacheStorage.has(contractAddress + tokenId) + const result = useSWR( contractAddress + tokenId, fetchNft, - { revalidateOnFocus: false } + { + revalidateOnMount: !cached, + revalidateOnFocus: false, + revalidateOnReconnect: false, + } ) return useMemo(() => {