| 1 | "use client"; |
| 2 | |
| 3 | import { useMutation, useQuery |
| 4 | import { toast } |
| 5 | |
| 6 | import { authClient } |
| 7 | |
| 8 | /** The organization behind `slug`, with members, invitations and teams, plus a way to change it that refreshes every organization query afterwards. */ |
| 9 | export function useOrganization(slug |
| 10 | const queryClient = |
| 11 | // Under "auth" with Better Auth UI's own queries, so one invalidation refreshes both. |
| 12 | const query = |
| 13 | queryKey: ["auth", |
| 14 | queryFn: async () |
| 15 | const { data, |
| 16 | { query: { organizationSlug: |
| 17 | ); |
| 18 | if (error) throw |
| 19 | return data; |
| 20 | }, |
| 21 | }); |
| 22 | |
| 23 | const change = |
| 24 | mutationFn: async ( |
| 25 | run, |
| 26 | }: { |
| 27 | run: () |
| 28 | done: string |
| 29 | }) => { |
| 30 | const { error |
| 31 | if (error) throw |
| 32 | }, |
| 33 | onSuccess: async ( |
| 34 | toast.success(done |
| 35 | await queryClient.invalidateQueries |
| 36 | }, |
| 37 | onError: (error: |
| 38 | }); |
| 39 | |
| 40 | return { |
| 41 | organization: query.data |
| 42 | isPending: query.isPending |
| 43 | busy: change.isPending |
| 44 | /** Runs one Better Auth organization call, toasts how it went, and resolves to whether it worked. */ |
| 45 | change: ( |
| 46 | run: () |
| 47 | done: string, |
| 48 | ) => |
| 49 | change.mutateAsync({ |
| 50 | () => true, |
| 51 | () => false, |
| 52 | ), |
| 53 | }; |
| 54 | } |