diff --git a/src/components/containers/sidebar.tsx b/src/components/containers/sidebar.tsx index b2fc163..d196ceb 100644 --- a/src/components/containers/sidebar.tsx +++ b/src/components/containers/sidebar.tsx @@ -13,7 +13,7 @@ import Button from "../ui/button"; import { themes } from "@/app/themes"; import appStore from "@/stores/app-store"; import garageLogo from "@/assets/garage-logo.svg"; -import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { useMutation } from "@tanstack/react-query"; import api from "@/lib/api"; import { toast } from "sonner"; import { useAuth } from "@/hooks/useAuth"; @@ -90,12 +90,10 @@ const Sidebar = () => { }; const LogoutButton = () => { - const queryClient = useQueryClient(); - const logout = useMutation({ mutationFn: () => api.post("/auth/logout"), onSuccess: () => { - queryClient.invalidateQueries({ queryKey: ["auth"] }); + window.location.href = "/auth/login"; }, onError: (err) => { toast.error(err?.message || "Unknown error"); diff --git a/src/lib/api.ts b/src/lib/api.ts index 4259944..16e6180 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -6,6 +6,16 @@ type FetchOptions = Omit & { export const API_URL = "/api"; +export class APIError extends Error { + status!: number; + + constructor(message: string, status: number = 400) { + super(message); + this.name = "APIError"; + this.status = status; + } +} + const api = { async fetch(url: string, options?: Partial) { const headers: Record = {}; @@ -36,13 +46,18 @@ const api = { ?.includes("application/json"); const data = isJson ? await res.json() : await res.text(); + if (res.status === 401 && !url.startsWith("/auth")) { + window.location.href = "/auth/login"; + throw new APIError("unauthorized", res.status); + } + if (!res.ok) { const message = isJson ? data?.message : typeof data === "string" ? data : res.statusText; - throw new Error(message); + throw new APIError(message, res.status); } return data as unknown as T;