-
Notifications
You must be signed in to change notification settings - Fork 589
/
Copy pathuse-favorites.ts
61 lines (52 loc) · 1.68 KB
/
use-favorites.ts
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
import {toast} from 'sonner'
import type {Favorite} from '@/features/files/types'
import {trpcReact} from '@/trpc/trpc'
import type {RouterError} from '@/trpc/trpc'
import {t} from '@/utils/i18n'
/**
* Hook to manage favorites in the file system.
* Provides functionality to fetch favorites, add/remove favorites, and check if an item is favorited.
*/
export function useFavorites() {
const utils = trpcReact.useContext()
// Query to fetch favorites
const {data: favorites, isLoading: isLoadingFavorites} = trpcReact.files.favorites.useQuery(undefined, {
keepPreviousData: true,
staleTime: 15_000,
onError: (error: RouterError) => {
console.error('Failed to fetch favorites:', error)
},
})
// Check if item is favorited
const isPathFavorite = (path: string) => favorites?.some((favorite: Favorite) => favorite.path === path)
// Add favorite mutation
const {mutateAsync: addFavorite, isLoading: isAddingFavorite} = trpcReact.files.addFavorite.useMutation({
onSuccess: async () => {
await utils.files.favorites.invalidate()
},
onError: (error: RouterError) => {
toast.error(t('files-error.add-favorite', {message: error.message}))
},
})
// Remove favorite mutation
const {mutateAsync: removeFavorite, isLoading: isRemovingFavorite} = trpcReact.files.deleteFavorite.useMutation({
onSuccess: async () => {
await utils.files.favorites.invalidate()
},
onError: (error: RouterError) => {
toast.error(t('files-error.remove-favorite', {message: error.message}))
},
})
return {
// Queries
favorites,
isLoadingFavorites,
isPathFavorite,
// Add favorite
addFavorite,
isAddingFavorite,
// Remove favorite
removeFavorite,
isRemovingFavorite,
}
}