File size: 1,477 Bytes
13ae717
 
 
8185bfc
13ae717
 
 
8185bfc
13ae717
 
 
 
 
 
 
 
 
 
 
 
 
8185bfc
 
 
 
 
13ae717
 
 
 
 
 
 
 
8185bfc
13ae717
 
 
8185bfc
13ae717
 
 
 
 
 
 
 
 
 
 
8185bfc
13ae717
 
8185bfc
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
/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";
import { useQuery, useQueryClient } from "@tanstack/react-query";

import { useRouter } from "next/navigation";

import { User } from "@/types";
import { isAuthenticated } from "@/lib/auth";
import { toast } from "sonner";

export const useUser = (initialData?: {
  user: User | null;
  errCode: number | null;
}) => {
  const client = useQueryClient();
  const router = useRouter();

  const { data: { user, errCode } = { user: null, errCode: null }, isLoading } =
    useQuery({
      queryKey: ["user.me"],
      queryFn: async () => {
        const authResult = await isAuthenticated();
        if (authResult && "id" in authResult) {
          return { user: authResult as User, errCode: null };
        }
        return { user: null, errCode: 401 };
      },
      refetchOnWindowFocus: false,
      refetchOnReconnect: false,
      refetchOnMount: false,
      retry: false,
      initialData: initialData
        ? { user: initialData?.user, errCode: initialData?.errCode }
        : undefined,
      enabled: true, // Enable the query to fetch the mock user
    });

  const logout = async () => {
    // Since authentication is removed, just reload the page
    toast.success("Logout successful");
    client.setQueryData(["user.me"], {
      user: null,
      errCode: null,
    });
    window.location.reload();
  };

  return {
    user,
    errCode,
    loading: isLoading,
    logout,
  };
};