-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGraphQLClientProvider.tsx
64 lines (57 loc) · 1.85 KB
/
GraphQLClientProvider.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { useEffect, useCallback, useMemo, useState } from "react"
import React from "react"
import { retryExchange } from "@urql/exchange-retry"
import axios from "axios"
import { useAuthContext } from "../hooks/useAuthContext"
import { Provider, createClient, dedupExchange, fetchExchange } from "urql"
import { cacheExchange, Cache } from "@urql/exchange-graphcache"
export const GraphQLClientProvider = ({ children }) => {
const client = useGraphQLClient()
return <Provider value={client}>{children}</Provider>
}
const invalidateCache = (cache: Cache, name: string, args?: { input: { id: any } }) =>
args
? cache.invalidate({ __typename: name, id: args.input.id })
: cache
.inspectFields("Query")
.filter((field) => field.fieldName === name)
.forEach((field) => {
cache.invalidate("Query", field.fieldKey)
})
const getGraphQLClient = (headers: HeadersInit) => {
const url = process.env.NEXT_PUBLIC_API_PATH
return createClient({
url: url,
fetchOptions: {
headers: headers,
},
exchanges: [
dedupExchange,
cacheExchange({
updates: {
Mutation: {
// Whenever we withdraw invalidate nfts
withdraw: (_parent, _args, cache, _info) => {
invalidateCache(cache, "nfts")
},
},
},
}),
retryExchange({ maxNumberAttempts: 3 }),
fetchExchange,
],
})
}
export const useGraphQLClient = () => {
const { session, isLoading } = useAuthContext()
return useMemo(() => {
const headers = {}
if (process.env.NEXT_PUBLIC_API_KEY) {
headers["X-Niftory-API-Key"] = process.env.NEXT_PUBLIC_API_KEY
}
if (session?.authToken || isLoading) {
headers["Authorization"] = `Bearer ${session?.authToken}`
}
return getGraphQLClient(headers)
}, [isLoading, session?.authToken])
}