add loading
This commit is contained in:
50
dashboard_js/app/hooks/use-auth.jsx
Normal file
50
dashboard_js/app/hooks/use-auth.jsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import { useMemo, useCallback, createContext, useState } from 'react'
|
||||
import * as Auth from 'aws-amplify/auth'
|
||||
|
||||
const AuthContext = createContext(null)
|
||||
|
||||
export function useAuth() {
|
||||
return useContext(AuthContext)
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }) {
|
||||
const [authUser, setAuthUser] = useState(null)
|
||||
|
||||
const currentUser = useCallback(async () => {
|
||||
try {
|
||||
const currentUser = await Auth.fetchUserAttributes()
|
||||
|
||||
setAuthUser(currentUser)
|
||||
return currentUser
|
||||
} catch {
|
||||
setAuthUser(null)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const signIn = useCallback(async ({ username, password }) => {
|
||||
const signInOut = await Auth.signIn({
|
||||
username,
|
||||
password,
|
||||
options: {
|
||||
clientMetadata: {},
|
||||
},
|
||||
})
|
||||
|
||||
if (signInOut?.isSignedIn) {
|
||||
setAuthUser(await Auth.fetchUserAttributes())
|
||||
}
|
||||
|
||||
return signInOut
|
||||
}, [])
|
||||
|
||||
const ctxValue = useMemo(
|
||||
() => ({
|
||||
authUser,
|
||||
signIn,
|
||||
currentUser,
|
||||
}),
|
||||
[authUser]
|
||||
)
|
||||
|
||||
return <AuthContext.Provider value={ctxValue}>{children}</AuthContext.Provider>
|
||||
}
|
||||
Reference in New Issue
Block a user