📖

JWT Authentication【18AuthContext Type】

2022/10/20に公開約1,300字

JWT Authentication【18AuthContext Type】

YouTube: https://youtu.be/9ts5znk-1so

src/types/user.tsx
export type LoginUser = {
  id: number
  name: string
  email: string
}
src/context/authContext.tsx
import { createContext, ReactNode, useContext, FC, useState } 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)
    }
  }

  return (
    <AuthContext.Provider value={{ user, setUser, login }}>
      {children}
    </AuthContext.Provider>
  )
}

export const useAuthContext = () => useContext(AuthContext)

Discussion

ログインするとコメントできます