Skip to content

Instantly share code, notes, and snippets.

@zerolethanh
Last active January 23, 2021 05:57
Show Gist options
  • Save zerolethanh/c56fc309f2628550141f16c5a438b2af to your computer and use it in GitHub Desktop.
Save zerolethanh/c56fc309f2628550141f16c5a438b2af to your computer and use it in GitHub Desktop.
Giữ trạng thái đăng nhập của với firebase.
import React, {createContext, useEffect, useState} from 'react';
import {useGlobal} from 'reactn';
import {useAuthState} from 'react-firebase-hooks/auth';
import {useDocument} from 'react-firebase-hooks/firestore';
const CFAuthContext = createContext({});
const useUser = ({auth, firestore}) => {
const [gUser, setGUser] = useGlobal('user');
const [user, loading, error] = useAuthState(auth);
const [doc, docLoading, docError] = useDocument(
user?.uid ? firestore?.doc(`users/${user.uid}`):undefined,
);
const [ready, setReady] = useState(false);
useEffect(() => {
if (loading || docLoading) return;
if (!user) {
setGUser(undefined, () => {
setReady(true);
});
return;
}
setGUser({
...user.toJSON(),
docId: doc?.id,
...doc?.data(),
}, () => {
setReady(true);
});
}, [user, loading, doc, docLoading, error, docError]);
return {
user: gUser || user?.toJSON(),
loading: loading || docLoading || !ready,
error: {error, docError},
};
};
const CFAuthProvider = ({auth, firestore, children}) => {
const val = useUser({auth, firestore});
return (
<CFAuthContext.Provider value={val}>
{children}
</CFAuthContext.Provider>
);
};
export {
CFAuthProvider,
CFAuthContext,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment