(auth?: MobileAuth)
| 9 | import { useSession } from "next-auth/react"; |
| 10 | |
| 11 | const useUser = (auth?: MobileAuth) => { |
| 12 | let status: "authenticated" | "loading" | "unauthenticated"; |
| 13 | let userId: string = ""; |
| 14 | |
| 15 | if (!auth) { |
| 16 | const { data, status: s } = useSession(); |
| 17 | status = s; |
| 18 | userId = (data?.user as any)?.id; |
| 19 | } else { |
| 20 | status = auth.status; |
| 21 | } |
| 22 | |
| 23 | const url = auth |
| 24 | ? auth?.instance + "/api/v1/users/me" |
| 25 | : "/api/v1/users/" + userId; |
| 26 | |
| 27 | return useQuery({ |
| 28 | queryKey: ["user"], |
| 29 | queryFn: async () => { |
| 30 | const response = await fetch( |
| 31 | url, |
| 32 | auth?.session |
| 33 | ? { |
| 34 | headers: { |
| 35 | Authorization: `Bearer ${auth.session}`, |
| 36 | }, |
| 37 | } |
| 38 | : undefined |
| 39 | ); |
| 40 | |
| 41 | if (!response.ok) throw new Error("Failed to fetch user data."); |
| 42 | |
| 43 | const data = (await response.json()).response as GetUserByIdResponse; |
| 44 | |
| 45 | if (!auth) |
| 46 | document.querySelector("html")?.setAttribute("data-theme", data.theme); |
| 47 | |
| 48 | return data; |
| 49 | }, |
| 50 | enabled: !auth |
| 51 | ? !!userId && status === "authenticated" |
| 52 | : status === "authenticated", |
| 53 | placeholderData: {} as GetUserByIdResponse, |
| 54 | }); |
| 55 | }; |
| 56 | |
| 57 | const useUpdateUser = () => { |
| 58 | const queryClient = useQueryClient(); |
no outgoing calls
no test coverage detected