1
0
mirror of https://github.com/oceanprotocol/market.git synced 2024-11-16 02:04:54 +01:00

create price provider

This commit is contained in:
Matthias Kretschmann 2020-10-28 10:32:56 +01:00
parent 071d811cd9
commit 47bd08e7a9
Signed by: m
GPG Key ID: 606EEEF3C479A91F
2 changed files with 72 additions and 1 deletions

View File

@ -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({
>
<UserPreferencesProvider>
<NetworkMonitor />
{element}
<PricesProvider>{element}</PricesProvider>
</UserPreferencesProvider>
</OceanProvider>
)

70
src/providers/Prices.tsx Normal file
View File

@ -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 (
<PricesContext.Provider value={{ prices }}>
{children}
</PricesContext.Provider>
)
}
// Helper hook to access the provider values
const usePrices = (): PricesValue => useContext(PricesContext)
export { PricesProvider, usePrices, PricesValue }