Login and working api with simple chat
This commit is contained in:
+34
-22
@@ -1,34 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import axios from "axios";
|
||||
import Cookies from "js-cookie";
|
||||
import { redirect } from "next/navigation";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export interface User {
|
||||
id: number;
|
||||
username: string;
|
||||
email: string;
|
||||
id: number;
|
||||
username: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export default function getUser() {
|
||||
const [user, setUser] = useState<undefined | User>();
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchUser() {
|
||||
const token = Cookies.get("token");
|
||||
export default function useUser() {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const router = useRouter();
|
||||
|
||||
if (!token) {
|
||||
redirect('/login')
|
||||
}
|
||||
useEffect(() => {
|
||||
async function fetchUser() {
|
||||
const token = Cookies.get("token");
|
||||
if (!token) {
|
||||
router.push("/login");
|
||||
return;
|
||||
}
|
||||
|
||||
const res = (await axios.get('http://localhost:3000/api/user', {
|
||||
params: { token }
|
||||
})).data as User;
|
||||
try {
|
||||
const res = (
|
||||
await axios.get("http://localhost:3000/api/user", {
|
||||
params: { token },
|
||||
})
|
||||
).data as User;
|
||||
|
||||
setUser(res);
|
||||
}
|
||||
|
||||
fetchUser();
|
||||
});
|
||||
setUser(res);
|
||||
} catch {
|
||||
router.push("/login");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return user;
|
||||
fetchUser();
|
||||
}, [router]);
|
||||
|
||||
return { user, loading };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user