Last active
December 17, 2020 14:08
-
-
Save Lowess/8e40ea5a40f03399ef16909e3538b966 to your computer and use it in GitHub Desktop.
Amplify authentication written in functional Preact using hooks
This file contains 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 { h } from 'preact'; | |
import { useState, useEffect, useContext } from 'preact/hooks'; | |
import { Hub } from '@aws-amplify/core'; | |
import { Auth } from '@aws-amplify/auth'; | |
import { UserContext } from '../contexts/UserContext'; | |
const AmplifyAuth = () => { | |
const [user, setUser] = useState(null); | |
const context = useContext(UserContext); | |
useEffect(() => { | |
Hub.listen("auth", ({ payload: { event, data } }) => { | |
switch (event) { | |
case "signIn": | |
setUser({ user: data }) | |
break; | |
case "signOut": | |
setUser({ user: null }) | |
break; | |
} | |
}) | |
Auth.currentAuthenticatedUser() | |
.then(user => { | |
setUser({ user }) | |
context.login(user) // Callback to store user data in the higher up context | |
}) | |
.catch(() => console.log("Not signed in")); | |
}, []); | |
return ( | |
<button class="btn btn-info" onClick={() => Auth.federatedSignIn({provider: 'Google'})}> | |
Signin with Google | |
</button> | |
); | |
} | |
export default AmplifyAuth; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment