From 659c1aac735bc6ab9f9b5ba357eb40b8c0c1b219 Mon Sep 17 00:00:00 2001 From: shams mosowi Date: Sun, 8 Sep 2019 18:35:32 +1000 Subject: [PATCH] firebase auth hook/context --- src/contexts/authContext.ts | 11 +++++++++++ src/hooks/useAuth.ts | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 src/contexts/authContext.ts create mode 100644 src/hooks/useAuth.ts diff --git a/src/contexts/authContext.ts b/src/contexts/authContext.ts new file mode 100644 index 00000000..d4c58ed0 --- /dev/null +++ b/src/contexts/authContext.ts @@ -0,0 +1,11 @@ +import React from "react"; + +interface AuthContextInterface { + authUser: firebase.User | null | undefined; +} + +const AuthContext = React.createContext({ + authUser: undefined +}); + +export default AuthContext; diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.ts new file mode 100644 index 00000000..a93e0c8d --- /dev/null +++ b/src/hooks/useAuth.ts @@ -0,0 +1,18 @@ +import { useEffect, useState } from "react"; +import { auth } from "../firebase"; + +const useAuth = () => { + const [authUser, setAuthUser] = useState( + undefined + ); + + useEffect(() => { + auth.onAuthStateChanged(token => { + setAuthUser(token); + }); + }, []); + + return authUser; +}; + +export default useAuth;