feat: 로그인 성공 시 토큰 저장 및 홈 스크린 이동
This commit is contained in:
@@ -1,24 +1,58 @@
|
||||
import React, { createContext, useContext, useMemo, useState } from "react";
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import React, {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react";
|
||||
import { loginApi } from "../api/auth";
|
||||
|
||||
const ACCESS_TOKEN_KEY = "accessToken";
|
||||
|
||||
export type AuthContextValue = {
|
||||
accessToken: string | null;
|
||||
isAuthed: boolean;
|
||||
login: () => void;
|
||||
logout: () => void;
|
||||
isHydrating: boolean; // 앱 시작 시 저장소에서 토큰 읽는 중인지
|
||||
signIn: (loginId: string, password: string) => Promise<void>;
|
||||
signOut: () => Promise<void>;
|
||||
};
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | null>(null);
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [isAuthed, setIsAuthed] = useState<boolean>(false);
|
||||
console.log("isAuthed: " + isAuthed);
|
||||
const [accessToken, setAccessToken] = useState<string | null>(null);
|
||||
const [isHydrating, setIsHydrating] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
const stored = await AsyncStorage.getItem(ACCESS_TOKEN_KEY);
|
||||
setAccessToken(stored);
|
||||
setIsHydrating(false);
|
||||
})();
|
||||
}, []);
|
||||
|
||||
const signIn = useCallback(async (loginId: string, password: string) => {
|
||||
const token = await loginApi({ loginId, password });
|
||||
setAccessToken(token);
|
||||
await AsyncStorage.setItem(ACCESS_TOKEN_KEY, token);
|
||||
}, []);
|
||||
|
||||
const signOut = useCallback(async () => {
|
||||
setAccessToken(null);
|
||||
await AsyncStorage.removeItem(ACCESS_TOKEN_KEY);
|
||||
}, []);
|
||||
|
||||
const value = useMemo<AuthContextValue>(
|
||||
() => ({
|
||||
isAuthed,
|
||||
login: () => setIsAuthed(true),
|
||||
logout: () => setIsAuthed(false),
|
||||
accessToken,
|
||||
isAuthed: accessToken != null,
|
||||
isHydrating,
|
||||
signIn,
|
||||
signOut,
|
||||
}),
|
||||
[isAuthed]
|
||||
[accessToken, isHydrating, signIn, signOut]
|
||||
);
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
|
||||
Reference in New Issue
Block a user