All files / src usePromiseStore.ts

100% Statements 11/11
100% Branches 2/2
100% Functions 4/4
100% Lines 10/10

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                                              35x   35x   20x 20x   20x 19x 18x     19x     20x         35x        
import { useCallback, useState } from 'react'
import { getOptionsCacheKey } from './getOptionsCacheKey'
import { FingerprintResponse } from './types'
import { UseVisitorDataOptions } from './useVisitorData'
 
export type UsePromiseStoreReturn = {
  /**
   *  Accepts a callback that returns a promise (`requestCallback`)
   *   and optional parameters (`options`). Ensures that the same request identified by a cache key is
   *   only executed once at a time, and returns the stored promise for the request. The promise is
   *   removed from the store once it is resolved or rejected.
   * */
  doRequest: (
    requestCallback: () => Promise<FingerprintResponse>,
    options?: UseVisitorDataOptions
  ) => Promise<FingerprintResponse>
}
 
/**
 * Manages a store of promises to handle unique asynchronous requests, ensuring that
 * requests with the same key are not duplicated while they are still pending.
 */
export function usePromiseStore(): UsePromiseStoreReturn {
  const [store] = useState(() => new Map<string, Promise<FingerprintResponse>>())
 
  const doRequest = useCallback(
    (requestCallback: () => Promise<FingerprintResponse>, options?: UseVisitorDataOptions) => {
      const cacheKey = getOptionsCacheKey(options)
      let cachedPromise = store.get(cacheKey)
 
      if (!cachedPromise) {
        cachedPromise = requestCallback().finally(() => {
          store.delete(cacheKey)
        })
 
        store.set(cacheKey, cachedPromise)
      }
 
      return cachedPromise
    },
    [store]
  )
 
  return {
    doRequest,
  }
}