more checks before using user data

This commit is contained in:
Oliver Bryan
2025-12-22 13:45:01 +00:00
parent 9747c376e6
commit 2385fed3b6

View File

@@ -24,18 +24,20 @@ export function Auth({ children }: AuthProviderProps) {
fetch(`${serverURL}/auth/me`, { fetch(`${serverURL}/auth/me`, {
headers: { Authorization: `Bearer ${token}` }, headers: { Authorization: `Bearer ${token}` },
}) })
.then((res) => res.json()) .then(async (res) => {
.then((data: UserRecord) => { if (!res.ok) {
if (data) { throw new Error(`auth check failed: ${res.status}`);
setLoggedIn(true);
localStorage.setItem("user", JSON.stringify(data));
} }
return (await res.json()) as UserRecord;
}) })
.catch((err) => { .then((data) => {
setLoggedIn(true);
localStorage.setItem("user", JSON.stringify(data));
})
.catch(() => {
setLoggedIn(false); setLoggedIn(false);
localStorage.removeItem("token"); localStorage.removeItem("token");
localStorage.removeItem("user"); localStorage.removeItem("user");
console.error("user not logged in:", err);
}); });
}, []); }, []);