Last change
on this file since 0f5aa27 was e6c2521, checked in by darsov2 <62809499+darsov2@…>, 10 months ago |
images upload/download impl, other fixes
|
-
Property mode
set to
100644
|
File size:
1.1 KB
|
Line | |
---|
1 | import React, { createContext, useContext, useState, useEffect } from 'react'
|
---|
2 |
|
---|
3 | const AuthContext = createContext()
|
---|
4 |
|
---|
5 | const AuthProvider = ({ children }) => {
|
---|
6 | const [user, setUser] = useState(null)
|
---|
7 |
|
---|
8 | useEffect(() => {
|
---|
9 | const storedUser = JSON.parse(localStorage.getItem('user'))
|
---|
10 | setUser(storedUser)
|
---|
11 | }, [])
|
---|
12 |
|
---|
13 | const getUser = () => {
|
---|
14 | return JSON.parse(localStorage.getItem('user'))
|
---|
15 | }
|
---|
16 |
|
---|
17 | const userIsAuthenticated = () => {
|
---|
18 | return localStorage.getItem('user') !== null
|
---|
19 | }
|
---|
20 |
|
---|
21 | const userLogin = user => {
|
---|
22 | localStorage.setItem('user', JSON.stringify(user))
|
---|
23 | setUser(user)
|
---|
24 | }
|
---|
25 |
|
---|
26 | const userLogout = () => {
|
---|
27 | localStorage.removeItem('user')
|
---|
28 | setUser(null)
|
---|
29 | }
|
---|
30 |
|
---|
31 | const contextValue = {
|
---|
32 | user,
|
---|
33 | getUser,
|
---|
34 | userIsAuthenticated,
|
---|
35 | userLogin,
|
---|
36 | userLogout,
|
---|
37 | }
|
---|
38 |
|
---|
39 | return (
|
---|
40 | <AuthContext.Provider value={contextValue}>
|
---|
41 | {children}
|
---|
42 | </AuthContext.Provider>
|
---|
43 | )
|
---|
44 | }
|
---|
45 |
|
---|
46 | export default AuthContext
|
---|
47 |
|
---|
48 | export function useAuth() {
|
---|
49 | return useContext(AuthContext)
|
---|
50 | }
|
---|
51 |
|
---|
52 | export { AuthProvider } |
---|
Note:
See
TracBrowser
for help on using the repository browser.