Skip to content

Instantly share code, notes, and snippets.

@sejr
Last active September 17, 2020 08:19
Show Gist options
  • Save sejr/febbadc33ee077ece19467e0d87a0199 to your computer and use it in GitHub Desktop.
Save sejr/febbadc33ee077ece19467e0d87a0199 to your computer and use it in GitHub Desktop.
Firebase Authentication with React Hooks
import React, { useState, useEffect } from 'react';
import { auth } from '../firebase';
type FirebaseUserState = firebase.User | null;
const SignIn = () => {
let [email, setEmail] = useState('');
let [password, setPassword] = useState('');
let [loading, setLoading] = useState(false);
const handleSubmit = () => {
setLoading(true);
auth.signInWithEmailAndPassword(email, password)
.then(() => {
console.log('success!');
})
.catch(error => {
console.error(error);
})
.finally(() => {
setLoading(false);
});
};
if (loading) {
return <p>Loading</p>;
} else {
return (
<div className="sign-in">
<input
type="email"
value={email}
placeholder="Email"
onChange={e => setEmail(e.target.value)}
/>
<input
type="password"
value={password}
placeholder="Password"
onChange={e => setPassword(e.target.value)}
/>
<button onClick={handleSubmit}>Sign In</button>
</div>
);
}
};
const Dashboard = () => {
const handleSignOut = () => {
auth.signOut();
};
return (
<div className="dashboard">
<h1>Hello!</h1>
<button onClick={handleSignOut}>Sign Out</button>
</div>
);
};
const App = () => {
let [currentUser, setUser] = useState<FirebaseUserState>(null);
useEffect(() => {
return auth.onAuthStateChanged(user => {
setUser(user);
});
});
return currentUser ? <Dashboard /> : <SignIn />;
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment