-
Notifications
You must be signed in to change notification settings - Fork 4
/
FingerprintJsProProvider.tsx
55 lines (49 loc) · 1.55 KB
/
FingerprintJsProProvider.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
import React, { PropsWithChildren, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { FingerprintJsProAgent } from './FingerprintJsProAgent'
import { FingerprintJsProContext } from './FingerprintJsProContext'
import { FingerprintJsProAgentParams, Tags } from './types'
/**
* Provides the FingerprintJsProContext to its child components.
*
* @example
* ```jsx
* <FingerprintJsProProvider
* apiKey: 'your-fpjs-public-api-key'
* >
* <MyApp />
* </FingerprintJsProProvider>
* ```
* @group Hooks approach
*/
export function FingerprintJsProProvider({
children,
...fingerprintJsProAgentParams
}: PropsWithChildren<FingerprintJsProAgentParams>) {
const [client, setClient] = useState<FingerprintJsProAgent>(
() => new FingerprintJsProAgent(fingerprintJsProAgentParams)
)
const [visitorId, updateVisitorId] = useState('')
const getVisitorData = useCallback(
async (tags?: Tags, linkedId?: string) => {
const result = await client.getVisitorData(tags, linkedId)
updateVisitorId(result.visitorId)
return result
},
[client]
)
const firstRender = useRef(true)
useEffect(() => {
if (firstRender) {
firstRender.current = false
} else {
setClient(new FingerprintJsProAgent(fingerprintJsProAgentParams))
}
}, [fingerprintJsProAgentParams])
const contextValue = useMemo(() => {
return {
visitorId,
getVisitorData,
}
}, [visitorId, getVisitorData])
return <FingerprintJsProContext.Provider value={contextValue}>{children}</FingerprintJsProContext.Provider>
}