about summary refs log tree commit diff
path: root/src/state/queries/notifications/settings.ts
blob: 986d0b01db3411e3441726a367a5d6007bcd2d1c (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import {type AppBskyNotificationDefs} from '@atproto/api'
import {t} from '@lingui/macro'
import {
  type QueryClient,
  useMutation,
  useQuery,
  useQueryClient,
} from '@tanstack/react-query'

import {logger} from '#/logger'
import {useAgent} from '#/state/session'
import * as Toast from '#/view/com/util/Toast'

const RQKEY_ROOT = 'notification-settings'
const RQKEY = [RQKEY_ROOT]

export function useNotificationSettingsQuery({
  enabled,
}: {enabled?: boolean} = {}) {
  const agent = useAgent()

  return useQuery({
    queryKey: RQKEY,
    queryFn: async () => {
      const response = await agent.app.bsky.notification.getPreferences()
      return response.data.preferences
    },
    enabled,
  })
}
export function useNotificationSettingsUpdateMutation() {
  const agent = useAgent()
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (
      update: Partial<AppBskyNotificationDefs.Preferences>,
    ) => {
      const response = await agent.app.bsky.notification.putPreferencesV2(
        update,
      )
      return response.data.preferences
    },
    onMutate: update => {
      optimisticUpdateNotificationSettings(queryClient, update)
    },
    onError: e => {
      logger.error('Could not update notification settings', {message: e})
      queryClient.invalidateQueries({queryKey: RQKEY})
      Toast.show(t`Could not update notification settings`, 'xmark')
    },
  })
}

function optimisticUpdateNotificationSettings(
  queryClient: QueryClient,
  update: Partial<AppBskyNotificationDefs.Preferences>,
) {
  queryClient.setQueryData(
    RQKEY,
    (old?: AppBskyNotificationDefs.Preferences) => {
      if (!old) return old
      return {...old, ...update}
    },
  )
}