33 lines
723 B
TypeScript
33 lines
723 B
TypeScript
![]() |
// 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 };
|
||
|
}
|