about summary refs log tree commit diff
path: root/src/state/queries/unstable-profile-cache.ts
blob: 72c3f86b8126c4fdb2a8dd0efef34a789a9dd11e (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
45
46
47
48
49
50
51
import {useCallback} from 'react'
import {type QueryClient, useQueryClient} from '@tanstack/react-query'

import type * as bsky from '#/types/bsky'

const unstableProfileViewCacheQueryKeyRoot = 'unstableProfileViewCache'
export const unstableProfileViewCacheQueryKey = (didOrHandle: string) => [
  unstableProfileViewCacheQueryKeyRoot,
  didOrHandle,
]

/**
 * Used as a rough cache of profile views to make loading snappier. This method
 * accepts and stores any profile view type by both handle and DID.
 *
 * Access the cache via {@link useUnstableProfileViewCache}.
 */
export function unstableCacheProfileView(
  queryClient: QueryClient,
  profile: bsky.profile.AnyProfileView,
) {
  queryClient.setQueryData(
    unstableProfileViewCacheQueryKey(profile.handle),
    profile,
  )
  queryClient.setQueryData(
    unstableProfileViewCacheQueryKey(profile.did),
    profile,
  )
}

/**
 * Hook to access the unstable profile view cache. This cache can return ANY
 * profile view type, so if the object shape is important, you need to use the
 * identity validators shipped in the atproto SDK e.g.
 * `AppBskyActorDefs.isValidProfileViewBasic` to confirm before using.
 *
 * To cache a profile, use {@link unstableCacheProfileView}.
 */
export function useUnstableProfileViewCache() {
  const qc = useQueryClient()
  const getUnstableProfile = useCallback(
    (didOrHandle: string) => {
      return qc.getQueryData<bsky.profile.AnyProfileView>(
        unstableProfileViewCacheQueryKey(didOrHandle),
      )
    },
    [qc],
  )
  return {getUnstableProfile}
}