init code
This commit is contained in:
56
src/context/auth-context.jsx
Normal file
56
src/context/auth-context.jsx
Normal file
@ -0,0 +1,56 @@
|
||||
import { STORE_KEY } from '@utils/enum'
|
||||
import { Helpers } from '@utils/helper'
|
||||
import { createContext, useCallback, useEffect, useMemo, useState } from 'react'
|
||||
|
||||
const AuthContext = createContext()
|
||||
|
||||
const DEFAULT_AUTH = {
|
||||
isLogged: false,
|
||||
userInfo: null,
|
||||
}
|
||||
|
||||
function getInitialAuth() {
|
||||
return Helpers.decrypt(localStorage.getItem(STORE_KEY), DEFAULT_AUTH)
|
||||
}
|
||||
|
||||
function AuthProvider({ children }) {
|
||||
const [auth, setAuth] = useState(getInitialAuth())
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem(STORE_KEY, Helpers.encrypt(auth))
|
||||
}, [auth])
|
||||
|
||||
const setLoggedIn = useCallback(
|
||||
(value) => {
|
||||
setAuth({
|
||||
...auth,
|
||||
isLogged: value,
|
||||
})
|
||||
},
|
||||
[auth],
|
||||
)
|
||||
|
||||
const setUserInfo = useCallback(
|
||||
(value) => {
|
||||
setAuth({
|
||||
...auth,
|
||||
userInfo: value,
|
||||
})
|
||||
},
|
||||
[auth],
|
||||
)
|
||||
|
||||
const context = useMemo(
|
||||
() => ({
|
||||
auth,
|
||||
setAuth,
|
||||
setLoggedIn,
|
||||
setUserInfo,
|
||||
}),
|
||||
[auth, setLoggedIn, setUserInfo],
|
||||
)
|
||||
|
||||
return <AuthContext.Provider value={context}>{children}</AuthContext.Provider>
|
||||
}
|
||||
|
||||
export { AuthContext, AuthProvider }
|
Reference in New Issue
Block a user