feat: 앱 시트·로그인 상태·지역 저장 틀, 공통 UI(Avatar·Chips·Rows·Credit)
This commit is contained in:
1 parent
e52f93fdbb
commit
28ff032160
8 files changed
+202
-15
No files matched your search
@@ -0,0 +1,37 @@
|
||||
import { clearTokens, getAccessToken, subscribeAuth } from '@nalssigak/shared/api/auth';
|
||||
import { meOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||
import { logout as logoutOnServer } from '@nalssigak/shared/api/client/sdk.gen';
|
||||
import type { Me } from '@nalssigak/shared/api/client/types.gen';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { createContext, use, useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react';
|
||||
|
||||
/** mePending: 토큰은 있고 내 정보를 받는 중 (아바타 자리를 비워 두지 않으려고) */
|
||||
export type AuthApi = { loggedIn: boolean; me: Me | null; mePending: boolean; logout: () => void };
|
||||
|
||||
const AuthContext = createContext<AuthApi | null>(null);
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = use(AuthContext);
|
||||
if (!ctx) throw new Error('useAuth must be used inside AuthProvider');
|
||||
return ctx;
|
||||
}
|
||||
|
||||
const subscribe = (cb: () => void) => subscribeAuth((reason) => reason === 'change' && cb());
|
||||
|
||||
/** 서버에서 이 계정의 토큰을 모두 무효로 만들고(실패해도) 기기 토큰을 지운다 */
|
||||
const logout = () => {
|
||||
void logoutOnServer({ throwOnError: false }).finally(clearTokens);
|
||||
};
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const token = useSyncExternalStore(subscribe, getAccessToken);
|
||||
const queryClient = useQueryClient();
|
||||
const me = useQuery({ ...meOptions(), enabled: !!token });
|
||||
|
||||
// 로그인·로그아웃하면 좋아요 여부가 달라지니 받아 둔 데이터를 다시 받는다
|
||||
useEffect(() => subscribeAuth((reason) => reason === 'change' && queryClient.invalidateQueries()), [queryClient]);
|
||||
|
||||
const mePending = !!token && me.isPending;
|
||||
const api = useMemo(() => ({ loggedIn: !!token, me: (token && me.data?.me) || null, mePending, logout }), [token, me.data, mePending]);
|
||||
return <AuthContext value={api}>{children}</AuthContext>;
|
||||
}
|
||||
Reference in new issue
Block a user