1
0

useHandleFollowChannel.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { useCallback } from 'react'
  2. import { useFollowChannel, useUnfollowChannel } from '@/api/hooks/channel'
  3. import { useConfirmationModal } from '@/providers/confirmationModal'
  4. import { usePersonalDataStore } from '@/providers/personalData'
  5. import { SentryLogger } from '@/utils/logs'
  6. export const useHandleFollowChannel = (id?: string, name?: string | null) => {
  7. const [openUnfollowDialog, closeUnfollowDialog] = useConfirmationModal()
  8. const { followChannel } = useFollowChannel()
  9. const { unfollowChannel } = useUnfollowChannel()
  10. const follow = usePersonalDataStore((state) => state.followedChannels.find((channel) => channel.id === id))
  11. const { followChannel: followChannelInStore, unfollowChannel: unfollowChannelInStore } = usePersonalDataStore(
  12. (state) => state.actions
  13. )
  14. const toggleFollowing = useCallback(async () => {
  15. if (!id || !name) {
  16. return
  17. }
  18. try {
  19. if (follow && follow.cancelToken) {
  20. openUnfollowDialog({
  21. type: 'warning',
  22. title: 'Do you want to unfollow?',
  23. description: `Unfollowing ${name} will no longer show new content from this channel on your following page.`,
  24. primaryButton: {
  25. text: 'Unfollow',
  26. onClick: () => {
  27. unfollowChannelInStore(id)
  28. unfollowChannel(id, follow.cancelToken)
  29. closeUnfollowDialog()
  30. },
  31. variant: 'destructive',
  32. },
  33. secondaryButton: {
  34. text: 'Keep following',
  35. onClick: () => {
  36. closeUnfollowDialog()
  37. },
  38. },
  39. })
  40. } else {
  41. const followResponse = await followChannel(id)
  42. const cancelToken = followResponse.data?.followChannel.cancelToken
  43. if (cancelToken) {
  44. followChannelInStore(id, cancelToken)
  45. }
  46. }
  47. } catch (error) {
  48. SentryLogger.error('Failed to update channel following', 'useHandleFollowChannel', error, { channel: { id } })
  49. }
  50. }, [
  51. id,
  52. name,
  53. follow,
  54. openUnfollowDialog,
  55. unfollowChannelInStore,
  56. unfollowChannel,
  57. closeUnfollowDialog,
  58. followChannel,
  59. followChannelInStore,
  60. ])
  61. return {
  62. toggleFollowing,
  63. isFollowing: !!follow,
  64. }
  65. }