All files useVisitorData.ts

95.83% Statements 23/24
50% Branches 3/6
100% Functions 3/3
95.83% Lines 23/24

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 68 69 70 71 72 73 74 75 76 77 78                                                      4x 4x 4x   4x   4x 4x     4x   4x 4x   3x 3x   3x   1x   1x   1x 1x 1x   1x     1x   4x       4x 4x         4x              
import type { VisitorData } from '@fingerprintjs/fingerprintjs-pro-spa'
import type { FpjsSvelteContext, FpjsSvelteQueryOptions } from './types'
import { writable } from 'svelte/store'
import { getContext, onMount } from 'svelte'
import { FPJS_CONTEXT } from './symbols'
import type { UseGetVisitorDataResult, UseVisitorDataOptions } from './useVisitorData.types'
 
/**
 * API for fetching visitorData.
 *
 * @example ```svelte
 *     <script>
 *       import { useVisitorData } from '@fingerprintjs/fingerprintjs-pro-svelte';
 *
 *       const { data, getData, isLoading, error } = useVisitorData(
 *          { extendedResult: true }
 *       );
 *
 *       // Fetch data on mount and ignore cache
 *       // const { data, getData, isLoading, error } = useVisitorData({ extendedResult: true, ignoreCache: true }, { immediate: true })
 *       </script>
 * ```
 * */
export function useVisitorData<TExtended extends boolean>(
  { ignoreCache: defaultIgnoreCache, ...options }: UseVisitorDataOptions<TExtended>,
  { immediate = true }: FpjsSvelteQueryOptions = {}
): UseGetVisitorDataResult<TExtended> {
  const dataValue = writable<VisitorData<TExtended> | undefined>(undefined)
  const loadingValue = writable(false)
  const errorValue = writable<Error | undefined>(undefined)
 
  const context = getContext<FpjsSvelteContext>(FPJS_CONTEXT)
 
  const getData: UseGetVisitorDataResult<TExtended>['getData'] = async (getDataOptions) => {
    loadingValue.set(true)
 
    const ignoreCache =
      typeof getDataOptions?.ignoreCache === 'boolean' ? getDataOptions.ignoreCache : defaultIgnoreCache
 
    try {
      const result = await context.getVisitorData(options, ignoreCache)
 
      dataValue.set(result)
      errorValue.set(undefined)
 
      return result
    } catch (error) {
      console.error(error)
 
      dataValue.set(undefined)
 
      if (error instanceof Error) {
        error.message = `${error.name}: ${error.message}`
        error.name = 'FPJSAgentError'
 
        errorValue.set(error)
      }
 
      return undefined
    } finally {
      loadingValue.set(false)
    }
  }
 
  onMount(async () => {
    Iif (immediate) {
      await getData()
    }
  })
 
  return {
    data: dataValue,
    error: errorValue,
    isLoading: loadingValue,
    getData,
  }
}