sum
This commit is contained in:
72
src/hooks/useCategories.ts
Normal file
72
src/hooks/useCategories.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { supabase } from "@/lib/supabase"
|
||||
import type { Category, CategoryType } from "@/lib/types"
|
||||
|
||||
export function useCategories() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ["categories"],
|
||||
queryFn: async () => {
|
||||
const { data, error } = await supabase
|
||||
.from("categories")
|
||||
.select("*")
|
||||
.order("type")
|
||||
.order("sort_order")
|
||||
if (error) throw error
|
||||
return data as Category[]
|
||||
},
|
||||
})
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: async (category: {
|
||||
name: string
|
||||
type: CategoryType
|
||||
icon?: string
|
||||
}) => {
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) throw new Error("Not authenticated")
|
||||
const { data, error } = await supabase
|
||||
.from("categories")
|
||||
.insert({ ...category, user_id: user.id })
|
||||
.select()
|
||||
.single()
|
||||
if (error) throw error
|
||||
return data as Category
|
||||
},
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["categories"] }),
|
||||
})
|
||||
|
||||
const update = useMutation({
|
||||
mutationFn: async ({
|
||||
id,
|
||||
...updates
|
||||
}: Partial<Category> & { id: string }) => {
|
||||
const { data, error } = await supabase
|
||||
.from("categories")
|
||||
.update(updates)
|
||||
.eq("id", id)
|
||||
.select()
|
||||
.single()
|
||||
if (error) throw error
|
||||
return data as Category
|
||||
},
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["categories"] }),
|
||||
})
|
||||
|
||||
const remove = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const { error } = await supabase.from("categories").delete().eq("id", id)
|
||||
if (error) throw error
|
||||
},
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["categories"] }),
|
||||
})
|
||||
|
||||
return {
|
||||
categories: query.data ?? [],
|
||||
loading: query.isLoading,
|
||||
create,
|
||||
update,
|
||||
remove,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user