Last active
February 8, 2023 07:48
-
-
Save KevinDanikowski/e99ccd210ae5303b2157fbcf8d53bb28 to your computer and use it in GitHub Desktop.
Amplify, React, Context API, Cognito, useAuth hook, NextJS, apollo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useContext, useState } from 'react' | |
import { useRouter } from 'next/router' | |
import Auth from '@aws-amplify/auth' | |
const UserContext = React.createContext() | |
export const initUser = { | |
user: null, | |
} | |
// user prop not currently used | |
export const UserProvider = ({ children, user }) => { | |
const [currentUserContext, setCurrentUserContext] = useState(user || initUser) | |
const setUserContext = values => { | |
setCurrentUserContext(values) | |
} | |
return <UserContext.Provider value={{ userContext: currentUserContext, setUserContext }}>{children}</UserContext.Provider> | |
} | |
export const UserConsumer = UserContext.Consumer | |
export function useAuth(redirect = false, path) { | |
const { userContext, setUserContext } = useContext(UserContext) | |
const router = useRouter() | |
useEffect(() => { | |
if (!userContext.user) { | |
let updateUser = async nothing => { | |
try { | |
let user = await Auth.currentAuthenticatedUser() | |
setUserContext({ user }) | |
// optional redirect to protected page (like dashboard) | |
if (path) { | |
router.push(path) | |
} | |
} catch { | |
// optional redirect to unprotected page (like home) | |
if (redirect) { | |
router.push('/unprotectedpage') | |
} | |
} | |
} | |
updateUser() | |
} | |
}, [userContext.user]) | |
return { user: userContext.user } | |
} | |
export default UserContext |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment