|
| 1 | +import React, { createContext, useContext, useState, useEffect } from 'react' |
| 2 | +import { useNavigate, useLocation } from 'react-router-dom'; |
| 3 | +import { userName, loginUser, logOut } from '../api/loginapi'; |
| 4 | + |
| 5 | + |
| 6 | +const AuthContext = createContext(); |
| 7 | + |
| 8 | +export const AuthProvider = ({children}) => { |
| 9 | + const [user, setUser] = useState(null) |
| 10 | + const [loading, setLoading] = useState(true) |
| 11 | + const nav = useNavigate() |
| 12 | + const location = useLocation(); |
| 13 | + |
| 14 | + const getAuthenticatedUser = async () => { |
| 15 | + try{ |
| 16 | + const user = await userName(); |
| 17 | + setUser(user); |
| 18 | + } catch (err) { |
| 19 | + |
| 20 | + setUser(null); |
| 21 | + }finally{ |
| 22 | + setLoading(false); |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + const logoutUser = async () => { |
| 27 | + try{ |
| 28 | + await logOut(); |
| 29 | + } catch (err) { |
| 30 | + console.log(err) |
| 31 | + } finally{ |
| 32 | + setUser(null) |
| 33 | + nav('/home') |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + // not yet used |
| 38 | + const registerUser = async (username, email, password, confirm_password) => { |
| 39 | + try { |
| 40 | + if (password === confirm_password) { |
| 41 | + await register(username, email, password) |
| 42 | + alert('User successfully registered') |
| 43 | + nav('/login') |
| 44 | + } |
| 45 | + } catch { |
| 46 | + alert('error registering user') |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + const login = async (username, password) => { |
| 51 | + const user = await loginUser(username, password) |
| 52 | + if (user) { |
| 53 | + setUser(user) |
| 54 | + nav('/tasks') |
| 55 | + } else { |
| 56 | + alert('Incorrect username or password') |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + useEffect(() => { |
| 61 | + getAuthenticatedUser(); |
| 62 | + }, [location.pathname]) |
| 63 | + |
| 64 | + return ( |
| 65 | + <AuthContext.Provider value={{ user, loading, login, logoutUser }}> |
| 66 | + {children} |
| 67 | + </AuthContext.Provider> |
| 68 | +); |
| 69 | + |
| 70 | + |
| 71 | +} |
| 72 | +export const useAuth = () => useContext(AuthContext); |
0 commit comments