🕌

JWT Authentication【17Login Method】

2022/10/19に公開

JWT Authentication【17Login Method】

YouTube: https://youtu.be/xmViefHEcjw

npm i axios
package.json
  "dependencies": {
    "axios": "^1.1.3",
  },
src/context/authContext.tsx
import { createContext, ReactNode, useContext, FC, useState } from 'react'
import axios from 'axios'

interface Props {
  children: ReactNode
}

const AuthContext = createContext({})

export const AuthProvider: FC<Props> = ({ children }) => {
  const [user, setUser] = useState(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