fix: redirect to login after logout

This commit is contained in:
Khairul Hidayat 2025-03-02 04:41:31 +07:00
parent 8c3458c27f
commit 04a10eadfd
2 changed files with 18 additions and 5 deletions

View File

@ -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");

View File

@ -6,6 +6,16 @@ type FetchOptions = Omit<RequestInit, "headers" | "body"> & {
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<T = any>(url: string, options?: Partial<FetchOptions>) {
const headers: Record<string, string> = {};
@ -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;