forked from
jollywhoppers.com/witchsky.app
Bluesky app fork with some witchin' additions 馃挮
1import React from 'react'
2import {useMutation, useQueryClient} from '@tanstack/react-query'
3
4import {STALE} from '#/state/queries'
5import {useAgent} from '#/state/session'
6
7const handleQueryKeyRoot = 'handle'
8const fetchHandleQueryKey = (handleOrDid: string) => [
9 handleQueryKeyRoot,
10 handleOrDid,
11]
12const didQueryKeyRoot = 'did'
13const fetchDidQueryKey = (handleOrDid: string) => [didQueryKeyRoot, handleOrDid]
14
15export function useFetchHandle() {
16 const queryClient = useQueryClient()
17 const agent = useAgent()
18
19 return React.useCallback(
20 async (handleOrDid: string) => {
21 if (handleOrDid.startsWith('did:')) {
22 const res = await queryClient.fetchQuery({
23 staleTime: STALE.MINUTES.FIVE,
24 queryKey: fetchHandleQueryKey(handleOrDid),
25 queryFn: () => agent.getProfile({actor: handleOrDid}),
26 })
27 return res.data.handle
28 }
29 return handleOrDid
30 },
31 [queryClient, agent],
32 )
33}
34
35export function useUpdateHandleMutation(opts?: {
36 onSuccess?: (handle: string) => void
37}) {
38 const queryClient = useQueryClient()
39 const agent = useAgent()
40
41 return useMutation({
42 mutationFn: async ({handle}: {handle: string}) => {
43 await agent.updateHandle({handle})
44 },
45 onSuccess(_data, variables) {
46 opts?.onSuccess?.(variables.handle)
47 queryClient.invalidateQueries({
48 queryKey: fetchHandleQueryKey(variables.handle),
49 })
50 },
51 })
52}
53
54export function useFetchDid() {
55 const queryClient = useQueryClient()
56 const agent = useAgent()
57
58 return React.useCallback(
59 async (handleOrDid: string) => {
60 return queryClient.fetchQuery({
61 staleTime: STALE.INFINITY,
62 queryKey: fetchDidQueryKey(handleOrDid),
63 queryFn: async () => {
64 let identifier = handleOrDid
65 if (!identifier.startsWith('did:')) {
66 const res = await agent.resolveHandle({handle: identifier})
67 identifier = res.data.did
68 }
69 return identifier
70 },
71 })
72 },
73 [queryClient, agent],
74 )
75}