Skip to content

Commit

Permalink
Merge pull request #520 from pankona/store-user-on-localstorage
Browse files Browse the repository at this point in the history
Store user on localStorage
  • Loading branch information
pankona committed May 6, 2022
2 parents 3d5e685 + 03d2485 commit 5e59730
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 17 deletions.
24 changes: 7 additions & 17 deletions hashira-web/src/firebase.ts
@@ -1,12 +1,5 @@
import { initializeApp } from "firebase/app";
import {
getAuth,
GoogleAuthProvider,
onAuthStateChanged as onFirebaseAuthStateChanged,
signInWithRedirect,
signOut,
User as FirebaseUser,
} from "firebase/auth";
import * as auth from "firebase/auth";
import {
addDoc,
collection,
Expand All @@ -23,7 +16,6 @@ import {
where,
} from "firebase/firestore";
import * as functions from "firebase/functions";

import { v4 as uuidv4 } from "uuid";

const firebaseConfig = {
Expand All @@ -39,22 +31,20 @@ const firebaseConfig = {
initializeApp(firebaseConfig);

export const login = () => {
const auth = getAuth();
const provider = new GoogleAuthProvider();
signInWithRedirect(auth, provider);
const provider = new auth.GoogleAuthProvider();
auth.signInWithRedirect(auth.getAuth(), provider);
};

export const logout = () => {
const auth = getAuth();
signOut(auth);
auth.signOut(auth.getAuth());
localStorage.removeItem("user");
};

export const onAuthStateChanged = (cb: (user: User | null) => void) => {
const auth = getAuth();
onFirebaseAuthStateChanged(auth, cb);
auth.onAuthStateChanged(auth.getAuth(), cb);
};

export type User = FirebaseUser;
export type User = auth.User;

interface accesstoken {
uid: string;
Expand Down
7 changes: 7 additions & 0 deletions hashira-web/src/hooks.ts
Expand Up @@ -212,12 +212,19 @@ export const useUser = () => {
const [state, setState] = React.useState<any | null | undefined>(undefined);

React.useEffect(() => {
const cachedUser = localStorage.getItem("user");
if (cachedUser) {
setState(JSON.parse(cachedUser));
}

firebase.onAuthStateChanged((user: firebase.User | null) => {
if (!user) {
setState(null);
localStorage.removeItem("user");
return;
}
setState(user);
localStorage.setItem("user", JSON.stringify(user));
});
}, []);

Expand Down

0 comments on commit 5e59730

Please sign in to comment.