about summary refs log tree commit diff
path: root/src/state/ageAssurance/useAgeAssurance.ts
blob: 06138486873d81993544d2c5d580b4cdcfe94c6b (plain) (blame)
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
import {useMemo} from 'react'

import {useAgeAssuranceContext} from '#/state/ageAssurance'
import {logger} from '#/state/ageAssurance/util'
import {usePreferencesQuery} from '#/state/queries/preferences'

type AgeAssurance = ReturnType<typeof useAgeAssuranceContext> & {
  /**
   * The age the user has declared in their preferences, if any.
   */
  declaredAge: number | undefined
  /**
   * Indicates whether the user has declared an age under 18.
   */
  isDeclaredUnderage: boolean
}

/**
 * Computed age information based on age assurance status and the user's
 * declared age. Use this instead of {@link useAgeAssuranceContext} to get a
 * more user-friendly interface.
 */
export function useAgeAssurance(): AgeAssurance {
  const aa = useAgeAssuranceContext()
  const {isFetched: preferencesLoaded, data: preferences} =
    usePreferencesQuery()
  const declaredAge = preferences?.userAge

  return useMemo(() => {
    const isReady = aa.isReady && preferencesLoaded
    const isDeclaredUnderage =
      declaredAge !== undefined ? declaredAge < 18 : false
    const state: AgeAssurance = {
      isReady,
      status: aa.status,
      lastInitiatedAt: aa.lastInitiatedAt,
      isAgeRestricted: aa.isAgeRestricted,
      declaredAge,
      isDeclaredUnderage,
    }
    logger.debug(`state`, state)
    return state
  }, [aa, preferencesLoaded, declaredAge])
}