|
| 1 | +import { createContext, useContext, useState, useEffect } from "react"; |
| 2 | +import { useNavigate } from "react-router-dom"; |
| 3 | +import { jwtDecode } from "jwt-decode"; |
| 4 | +import { enqueueSnackbar } from 'notistack'; |
| 5 | +import api from "./api"; |
| 6 | + |
| 7 | +const AppContext = createContext(); |
| 8 | + |
| 9 | +export const useAppContext = () => { |
| 10 | + return useContext(AppContext); |
| 11 | +}; |
| 12 | + |
| 13 | +export const AppContextProvider = ({ children }) => { |
| 14 | + const accessToken = localStorage.getItem("access"); |
| 15 | + const refreshToken = localStorage.getItem("refresh"); |
| 16 | + let [ inputData, setInputData ] = useState({}); |
| 17 | + const [user, setUser] = useState(null); |
| 18 | + const [ branches, setBranches ] = useState([]); |
| 19 | + const [loading, setLoading] = useState(false); |
| 20 | + const [auth, setAuth] = useState(false); |
| 21 | + const navigate = useNavigate(); |
| 22 | + |
| 23 | + // auth confirmation |
| 24 | + useEffect(() => { |
| 25 | + const access_token = localStorage.getItem("access"); |
| 26 | + if (access_token) { |
| 27 | + const decoded = jwtDecode(access_token); |
| 28 | + setUser(decoded); |
| 29 | + setAuth(true); |
| 30 | + } |
| 31 | + setLoading(false); |
| 32 | + }, []); |
| 33 | + |
| 34 | + // Input Change |
| 35 | + function handleInputChange(e){ |
| 36 | + let name = e.target.name; |
| 37 | + let value = e.target.value; |
| 38 | + |
| 39 | + if (e.target.type === 'select-one'){ |
| 40 | + value = e.target.options[e.target.selectedIndex].value; |
| 41 | + } |
| 42 | + |
| 43 | + setInputData(current => ({...current, [name]: value})); |
| 44 | + } |
| 45 | + |
| 46 | + // User Register |
| 47 | + async function registerUser() { |
| 48 | + try { |
| 49 | + setLoading(true); |
| 50 | + const response = await api.post('users/register/', inputData); |
| 51 | + if (response.status === 201) { |
| 52 | + navigate('/signin') |
| 53 | + } |
| 54 | + } catch (error) { |
| 55 | + console.log(error); |
| 56 | + } finally { |
| 57 | + setInputData({}); |
| 58 | + setLoading(false); |
| 59 | + } |
| 60 | + }; |
| 61 | + |
| 62 | + // User Login |
| 63 | + async function tokenSignIn() { |
| 64 | + try { |
| 65 | + setLoading(true); |
| 66 | + const response = await api.post('token/', inputData); |
| 67 | + if (response.status === 200) { |
| 68 | + localStorage.setItem('access', response.data.access); |
| 69 | + localStorage.setItem('refresh', response.data.refresh); |
| 70 | + setAuth(true); |
| 71 | + navigate('/'); |
| 72 | + } |
| 73 | + } catch (error) { |
| 74 | + console.log(error); |
| 75 | + } finally { |
| 76 | + setInputData({}); |
| 77 | + setLoading(false); |
| 78 | + } |
| 79 | + }; |
| 80 | + |
| 81 | + // User Logout |
| 82 | + const handleLogout = async () => { |
| 83 | + if (!refreshToken) { |
| 84 | + alert('No refresh token found!'); |
| 85 | + return; |
| 86 | + } |
| 87 | + |
| 88 | + try { |
| 89 | + setLoading(true); |
| 90 | + const res = await api.post('logout/', { 'refresh_token': refreshToken }); |
| 91 | + if (res.status === 205) { |
| 92 | + setAuth(false); |
| 93 | + localStorage.removeItem('access'); |
| 94 | + localStorage.removeItem('refresh'); |
| 95 | + navigate('/signin'); |
| 96 | + enqueueSnackbar(`Successfully Logged Out!`, { variant: 'success' }); |
| 97 | + } |
| 98 | + } catch (error) { |
| 99 | + enqueueSnackbar('Error Logging Out!', { variant: 'error' }) |
| 100 | + console.error('Logout Error:', error); |
| 101 | + } finally { |
| 102 | + setLoading(false); |
| 103 | + } |
| 104 | + }; |
| 105 | + |
| 106 | + // Branches GET |
| 107 | + async function fetchBranches() { |
| 108 | + try { |
| 109 | + setLoading(true); |
| 110 | + const response = await api.get('branches/'); |
| 111 | + if (response.status === 200){ |
| 112 | + setBranches(response.data) |
| 113 | + } |
| 114 | + } catch (error) { |
| 115 | + console.log(error); |
| 116 | + } finally { |
| 117 | + setLoading(false); |
| 118 | + } |
| 119 | + }; |
| 120 | + |
| 121 | + // Scroll to top |
| 122 | + function scrollToTop() { |
| 123 | + document.body.scrollTop = 0; // Safari |
| 124 | + document.documentElement.scrollTop = 0; //Chrome, Firefox, IE and Opera |
| 125 | + }; |
| 126 | + |
| 127 | + useEffect(() => { |
| 128 | + fetchBranches(); |
| 129 | + }, []); |
| 130 | + |
| 131 | + const contextValues = { |
| 132 | + user, |
| 133 | + setUser, |
| 134 | + handleInputChange, |
| 135 | + registerUser, |
| 136 | + tokenSignIn, |
| 137 | + handleLogout, |
| 138 | + branches, |
| 139 | + setBranches, |
| 140 | + loading, |
| 141 | + setLoading, |
| 142 | + auth, |
| 143 | + setAuth, |
| 144 | + scrollToTop, |
| 145 | + navigate |
| 146 | + }; |
| 147 | + |
| 148 | + return ( |
| 149 | + <AppContext.Provider |
| 150 | + value={contextValues} |
| 151 | + > |
| 152 | + {children} |
| 153 | + </AppContext.Provider> |
| 154 | + ); |
| 155 | +}; |
0 commit comments