I am using Firebase
to authenticate users for my application. I have created the SignIn
and SignUp
forms and can successfully create n
You can write a Custom Hook
which registers an effect and returns the auth state
const useFirebaseAuthentication = (firebase) => {
const [authUser, setAuthUser] = useState(null);
useEffect(() =>{
const unlisten = firebase.auth.onAuthStateChanged(
authUser => {
authUser
? setAuthUser(authUser)
: setAuthUser(null);
},
);
return () => {
unlisten();
}
});
return authUser
}
export default useFirebaseAuthentication;
and in any Component
you can use it like
const MyComponent = (props) => {
const firebase = useContext(FirebaseContext);
const authUser = useFirebaseAuthentication(firebase);
return (...)
}
Index.jsx
will have this code in it
ReactDOM.render(
<FirebaseProvider>
<App />
</FirebaseProvider>,
document.getElementById('root'));
This Firebase Provider is defined like this,
import Firebase from './firebase';
const FirebaseContext = createContext();
export const FirebaseProvider = (props) => (
<FirebaseContext.Provider value={new Firebase()}>
{props.children}
</FirebaseContext.Provider>
);
Hi the information from Shubham Khatri was very helpful and helped me to build my own component but he used Context to manage the state. If you just start learning react and firebase I found it easyer (even if not right) to have the state in my component.
So the simple solution for me without using Context was to build it with react hooks only like this:
const useAuth = () => {
const fireUser = firebase.auth().currentUser;
const [user, setUser] = useState(fireUser);
useEffect(() => {
const unsub = firebase.auth().onAuthStateChanged((user) => {
user ? setUser(user) : setUser(null);
});
return () => {
unsub();
};
});
return user;
};
const HomeV2 = () => {
const user = useAuth();
return (
<div>
<Link to="/">React Hooks </Link>
<LogPage />
{user ? <p>User is HERE</p> : <p>There's no user !</p>}
</div>
);
};
export default HomeV2;