2021-06-22 07:52:49 +02:00
|
|
|
import { createClient, Provider, Client } from 'urql'
|
|
|
|
import React, { useState, useEffect, ReactNode, ReactElement } from 'react'
|
2021-07-02 08:44:24 +02:00
|
|
|
import { Logger } from '@oceanprotocol/lib'
|
2021-10-18 20:44:33 +02:00
|
|
|
import { getOceanConfig } from '@utils/ocean'
|
2021-06-22 07:52:49 +02:00
|
|
|
|
|
|
|
let urqlClient: Client
|
|
|
|
|
|
|
|
function createUrqlClient(subgraphUri: string) {
|
|
|
|
const client = createClient({
|
|
|
|
url: `${subgraphUri}/subgraphs/name/oceanprotocol/ocean-subgraph`
|
|
|
|
})
|
|
|
|
return client
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getUrqlClientInstance(): Client {
|
|
|
|
return urqlClient
|
|
|
|
}
|
|
|
|
|
|
|
|
export default function UrqlClientProvider({
|
|
|
|
children
|
|
|
|
}: {
|
|
|
|
children: ReactNode
|
|
|
|
}): ReactElement {
|
2021-08-17 11:46:51 +02:00
|
|
|
//
|
|
|
|
// Set a default client here based on ETH Mainnet, as that's required for
|
|
|
|
// urql to work.
|
|
|
|
// Throughout code base this client is then used and altered by passing
|
|
|
|
// a new queryContext holding different subgraph URLs.
|
|
|
|
//
|
2021-06-22 07:52:49 +02:00
|
|
|
const [client, setClient] = useState<Client>()
|
|
|
|
|
|
|
|
useEffect(() => {
|
2021-08-17 11:46:51 +02:00
|
|
|
const oceanConfig = getOceanConfig(1)
|
2021-06-22 07:52:49 +02:00
|
|
|
|
|
|
|
if (!oceanConfig?.subgraphUri) {
|
|
|
|
Logger.error(
|
|
|
|
'No subgraphUri defined, preventing UrqlProvider from initialization.'
|
|
|
|
)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
const newClient = createUrqlClient(oceanConfig.subgraphUri)
|
|
|
|
urqlClient = newClient
|
|
|
|
setClient(newClient)
|
2021-07-02 08:44:24 +02:00
|
|
|
Logger.log(`[URQL] Client connected to ${oceanConfig.subgraphUri}`)
|
2021-08-17 11:46:51 +02:00
|
|
|
}, [])
|
2021-06-22 07:52:49 +02:00
|
|
|
|
|
|
|
return client ? <Provider value={client}>{children}</Provider> : <></>
|
|
|
|
}
|
2021-08-17 11:46:51 +02:00
|
|
|
|
2021-06-22 07:52:49 +02:00
|
|
|
export { UrqlClientProvider }
|