😽
JWT Authentication【23Check Login by JWT】
JWT Authentication【23Check Login by JWT】
YouTube: https://youtu.be/X_k8EwYWlBI
今回はリロードされてもログイン状態が維持できるように
JWTでユーザー情報を取得する部分の実装になります。
色々やり方はあるのですが、
今回はファイル構成がわかりやすいように
authContext内で処理を実装します。
src/context/authContext.tsx
import {
createContext,
ReactNode,
useContext,
FC,
useState,
useEffect,
} from 'react'
import axios from 'axios'
import { LoginUser } from '../types/user'
interface Props {
children: ReactNode
}
interface AuthContextType {
user: LoginUser | null
setUser: React.Dispatch<React.SetStateAction<LoginUser | null>>
login: (email: string, password: string) => Promise<void>
}
const AuthContext = createContext({} as AuthContextType)
export const AuthProvider: FC<Props> = ({ children }) => {
const [user, setUser] = useState<LoginUser | null>(null)
const login = async (email: string, password: string) => {
try {
const res = await axios.post(
`http://localhost:4000/api/auth/login`,
{
email,
password,
},
{ withCredentials: true }
)
setUser(res.data)
} catch (error: any) {
console.log(error.response.data)
}
}
const checkIsLogin = async () => {
try {
const res = await axios.get(`http://localhost:4000/api/auth/me`, {
withCredentials: true,
})
setUser(res.data)
} catch (error: any) {
console.log(error.response.data)
setUser(null)
}
}
useEffect(() => {
checkIsLogin()
}, [])
return (
<AuthContext.Provider value={{ user, setUser, login }}>
{children}
</AuthContext.Provider>
)
}
export const useAuthContext = () => useContext(AuthContext)
Discussion