- fix issue with firebase-hooks

- implement custom useAuthState
This commit is contained in:
Amruth Pillai
2020-07-06 19:53:47 +05:30
parent 862ff7cdc1
commit 4e064dba96
11 changed files with 465 additions and 157 deletions

54
src/hooks/useAuthState.js Normal file
View File

@ -0,0 +1,54 @@
import { useEffect, useReducer, useState } from "react";
export default function useAuthState(firebase) {
const [auth, setAuth] = useState(undefined);
const [state, dispatch] = useReducer(
(state, action) => {
switch (action.type) {
case "auth_state_changed":
return {
...state,
user: action.user,
loading: false,
};
case "error":
return {
...state,
error: action.error,
loading: false,
};
default:
return state;
}
},
{
user: undefined,
loading: true,
error: undefined,
}
);
useEffect(() => {
setAuth(firebase.auth());
}, [firebase]);
useEffect(() => {
if (auth === undefined) return;
const unsubscribe = auth.onAuthStateChanged(
(user) => {
dispatch({ type: "auth_state_changed", user });
},
(error) => {
dispatch({ type: "error", error });
}
);
return () => {
unsubscribe();
};
}, [auth]);
return [state.user, state.loading, state.error];
}