fix: useEffect와 useState를 활용하여 useLogin 훅 개선 및 무한 루프 방지 로직 제거
This commit is contained in:
parent
f3a41a5e8c
commit
4dc2ee0cab
1 changed files with 12 additions and 25 deletions
|
@ -7,7 +7,7 @@ import {
|
|||
refreshService,
|
||||
resetPasswordService,
|
||||
} from "./api.ts";
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
let localObj: LoginResponse | null = null;
|
||||
|
||||
|
@ -135,32 +135,19 @@ export const doResetPassword = async (username: string, oldpassword: string, new
|
|||
}
|
||||
};
|
||||
|
||||
let imutableSnapshot: ReturnType<typeof getUserSessions> = getUserSessions();
|
||||
const getSnapshot = () => {
|
||||
const snap = getUserSessions();
|
||||
// to avoid infinite loop, do not update the snapshot if it hasn't changed
|
||||
if (JSON.stringify(snap) === JSON.stringify(imutableSnapshot)) {
|
||||
return imutableSnapshot;
|
||||
}
|
||||
return snap;
|
||||
}
|
||||
const subscribe = (onChange: () => void) => {
|
||||
console.log("Auth hook subscribed");
|
||||
const listener = () => {
|
||||
console.log("Auth state changed, updating hook");
|
||||
imutableSnapshot = getSnapshot();
|
||||
onChange();
|
||||
};
|
||||
window.addEventListener("auth", listener);
|
||||
return () => window.removeEventListener("auth", listener);
|
||||
}
|
||||
|
||||
export function useLogin() {
|
||||
const hook = useSyncExternalStore(
|
||||
subscribe,
|
||||
getUserSessions,
|
||||
);
|
||||
return hook;
|
||||
const [user, setUser] = useState(getUserSessions());
|
||||
useEffect(() => {
|
||||
const listener = (_e: AuthEvent) => {
|
||||
setUser(getUserSessions());
|
||||
};
|
||||
window.addEventListener("auth", listener);
|
||||
return () => {
|
||||
window.removeEventListener("auth", listener);
|
||||
};
|
||||
}, []);
|
||||
return user;
|
||||
}
|
||||
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue