Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache NFT data between mounts #59

Merged
merged 2 commits into from
May 5, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 23 additions & 6 deletions src/core.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -67,16 +67,27 @@ function normalizeFetcher(fetcher: FetcherProp): Fetcher<unknown> {

const NftContext = createContext<{
fetcher?: Fetcher<unknown> | null
cacheStorage: Map<string, unknown>
} | null>(null)

const NftProvider: FC<{
children: ReactNode
fetcher?: Fetcher<unknown> | 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 (
<NftContext.Provider value={{ fetcher: normalizeFetcher(fetcher) }}>
{children}
</NftContext.Provider>
<SWRConfig value={{ cache: swrCache }}>
<NftContext.Provider value={contextValue}>{children}</NftContext.Provider>
</SWRConfig>
)
}

Expand All @@ -86,18 +97,24 @@ function useNft(contractAddress: Address, tokenId: string): NftResult {
throw new Error("Please wrap your app with <NftProvider />")
}

const { fetcher } = context
const { fetcher, cacheStorage } = context

const fetchNft = useCallback(() => {
return fetcher
? fetcher.fetchNft(contractAddress, tokenId)
: { ...NFT_METADATA_DEFAULT }
}, [contractAddress, fetcher, tokenId])

const cached = cacheStorage.has(contractAddress + tokenId)

const result = useSWR<NftMetadata, Error>(
contractAddress + tokenId,
fetchNft,
{ revalidateOnFocus: false }
{
revalidateOnMount: !cached,
revalidateOnFocus: false,
revalidateOnReconnect: false,
}
)

return useMemo(() => {
Expand Down