duckil_plm/fems-app/src/hooks/useAuth.ts

33 lines
723 B
TypeScript
Raw Normal View History

2024-11-02 07:15:56 +09:00
// src/hooks/useAuth.ts
import { useRouter } from "next/navigation";
import { useAuthStore } from "@/stores/auth";
import { api } from "@/lib/api";
export function useAuth() {
const router = useRouter();
const { user, token, setAuth, clearAuth } = useAuthStore();
const login = async ({
username,
password,
}: {
username: string;
password: string;
}) => {
try {
const { data } = await api.post("/auth/login", { username, password });
setAuth(data.user, data.token);
router.push("/dashboard/overview");
} catch (error) {
throw error;
}
};
const logout = () => {
clearAuth();
router.push("/login");
};
return { user, token, login, logout };
}