Skip to content
Snippets Groups Projects
useAuth.ts 948 B
Newer Older
  • Learn to ignore specific revisions
  • import React, { useState, useContext } from 'react'
    import { useHistory } from 'react-router-dom'
    import axios from 'axios'
    import { UserContext } from './userContext'
    import { User } from '../models/user.model'
    
    const _apiUrl: string = 'https://localhost:1443/'
    
    export interface Auth {
      user: User
      setUser: React.Dispatch<any>
      loginUser: () => void
      error: null
      isLogged: boolean
    }
    export const useAuth = (): Auth => {
      const [user, setUser] = useState<any>(null)
      const [isLogged, setisLogged] = useState(false)
      const [error, setError] = useState(null)
    
      //login user
      const loginUser = async () => {
        try {
          await axios.get(`${_apiUrl}OAuth2Login`)
          const { data } = await axios.get(`${_apiUrl}api/common/WhoAmI`)
          if (data) {
            setisLogged(true)
            console.log(data)
            setUser(data)
          }
        } catch (e) {
          setError(e)
        }
      }
      return { user, setUser, loginUser, error, isLogged }
    }