Skip to content

Instantly share code, notes, and snippets.

@Lowess
Last active December 17, 2020 14:08
Show Gist options
  • Save Lowess/8e40ea5a40f03399ef16909e3538b966 to your computer and use it in GitHub Desktop.
Save Lowess/8e40ea5a40f03399ef16909e3538b966 to your computer and use it in GitHub Desktop.
Amplify authentication written in functional Preact using hooks
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