From 47bd08e7a981aa280197e3dc20f1acc93373571d Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Wed, 28 Oct 2020 10:32:56 +0100 Subject: [PATCH] create price provider --- src/helpers/wrapRootElement.tsx | 3 +- src/providers/Prices.tsx | 70 +++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 src/providers/Prices.tsx diff --git a/src/helpers/wrapRootElement.tsx b/src/helpers/wrapRootElement.tsx index e00ebe1c0..b99bbcc49 100644 --- a/src/helpers/wrapRootElement.tsx +++ b/src/helpers/wrapRootElement.tsx @@ -9,6 +9,7 @@ import { ConfigHelperNetworkId } from '@oceanprotocol/lib/dist/node/utils/ConfigHelper' import { UserPreferencesProvider } from '../providers/UserPreferences' +import PricesProvider from '../providers/Prices' export function getOceanConfig( network: ConfigHelperNetworkName | ConfigHelperNetworkId @@ -34,7 +35,7 @@ export default function wrapRootElement({ > - {element} + {element} ) diff --git a/src/providers/Prices.tsx b/src/providers/Prices.tsx new file mode 100644 index 000000000..2fb757cf7 --- /dev/null +++ b/src/providers/Prices.tsx @@ -0,0 +1,70 @@ +import React, { + useState, + useEffect, + ReactElement, + createContext, + useContext, + ReactNode +} from 'react' +import { fetchData } from '../utils' +import useSWR from 'swr' +import { useSiteMetadata } from '../hooks/useSiteMetadata' +import { Logger } from '@oceanprotocol/lib' + +interface PricesValue { + prices: { + [key: string]: number + } +} + +const initialData: PricesValue = { + prices: { + eur: 0.0, + usd: 0.0, + eth: 0.0, + btc: 0.0 + } +} + +const PricesContext = createContext(null) + +export default function PricesProvider({ + children +}: { + children: ReactNode +}): ReactElement { + const { appConfig } = useSiteMetadata() + const tokenId = 'ocean-protocol' + const currencies = appConfig.currencies.join(',') // comma-separated list + const url = `https://api.coingecko.com/api/v3/simple/price?ids=${tokenId}&vs_currencies=${currencies}&include_24hr_change=true` + + const [prices, setPrices] = useState(initialData) + + const { data } = useSWR(url, fetchData, { + initialData, + refreshInterval: 30000, // 30 sec. + // eslint-disable-next-line @typescript-eslint/no-use-before-define + onSuccess + }) + + async function onSuccess() { + if (!data) return + Logger.log(`Got new prices. ${JSON.stringify(data)}`) + setPrices(data) + } + + useEffect(() => { + onSuccess() + }, [data]) + + return ( + + {children} + + ) +} + +// Helper hook to access the provider values +const usePrices = (): PricesValue => useContext(PricesContext) + +export { PricesProvider, usePrices, PricesValue }