Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 65 66 67 | 34x 34x 4x 34x 34x 34x 7x 4x 4x 34x 34x 22x 18x 4x 34x 25x 34x | import React, { PropsWithChildren, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { FingerprintJsProAgent } from './FingerprintJsProAgent'
import { FingerprintJsProContext } from './FingerprintJsProContext'
import { FingerprintJsProAgentParams, RequestOptions, Tags } from './types'
import { deepEqual } from './utils'
/**
* Provides the FingerprintJsProContext to its child components.
*
* @example
* ```jsx
* <FingerprintJsProProvider
* apiKey: 'your-fpjs-public-api-key'
* requestOptions: { timeout: 5000 } // Optional: Set a custom timeout in milliseconds
* >
* <MyApp />
* </FingerprintJsProProvider>
* ```
* @group Hooks approach
*/
export function FingerprintJsProProvider({
children,
...fingerprintJsProAgentParams
}: PropsWithChildren<FingerprintJsProAgentParams>) {
// `fingerprintJsProAgentParams` is a fresh object on every render (rest spread), so we cannot depend on
// its identity. Keep a stable reference that only changes when the params change by value. This also
// spares consumers from having to memoize inline object/array props (e.g. `requestOptions`).
const [stableAgentParams, setStableAgentParams] = useState(fingerprintJsProAgentParams)
if (
!Object.is(stableAgentParams, fingerprintJsProAgentParams) &&
!deepEqual(stableAgentParams, fingerprintJsProAgentParams)
) {
setStableAgentParams(fingerprintJsProAgentParams)
}
const [client, setClient] = useState<FingerprintJsProAgent>(() => new FingerprintJsProAgent(stableAgentParams))
const [visitorId, setVisitorId] = useState('')
const getVisitorData = useCallback(
async (tags?: Tags, linkedId?: string, requestOptions?: RequestOptions) => {
const result = await client.getVisitorData(tags, linkedId, requestOptions)
setVisitorId(result.visitorId)
return result
},
[client]
)
const firstRenderRef = useRef(true)
useEffect(() => {
if (firstRenderRef.current) {
firstRenderRef.current = false
} else {
setClient(new FingerprintJsProAgent(stableAgentParams))
}
}, [stableAgentParams])
const contextValue = useMemo(() => {
return {
visitorId,
getVisitorData,
}
}, [visitorId, getVisitorData])
return <FingerprintJsProContext.Provider value={contextValue}>{children}</FingerprintJsProContext.Provider>
}
|