CLASSFUNC BLOG
We Share Our Knowledge
Giữ trạng thái login logout với CFAuthProvider
ReactJS
Lê Thành
16 Th01 2021 06:18

CFAuthProvider.png

Khi chúng ta làm một app có đăng nhập thì chúng ta phải giữ trạng thái đăng nhập của app nếu người dùng đã login và redirect tới trang login nếu người dùng không ở trạng thái đã login (logout). Bài viết này mình chia sẻ kinh nghiệm về cách lưu trữ trạng thái login logout của app khi dùng Firebase trong React. Mời các bạn tham khảo.

Video dưới là cách Ví Của Tui sử dụng CFAuthProvider

Chuẩn bị:

  1. Kiến thức về Context (xem tại https://reactjs.org/docs/context.html)

Tóm tắt các bước:

  1. Tạo firebase app (nếu chưa có)
  2. Sử dụng CFAuthProvider

0. CFAuthProvider

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, };

1. Tạo firebase app

1.1 Nếu chưa có firebase config tạo 1 project Firebase ở https://console.firebase.google.com/u/0/

1.2 Tạo file init app Firebase

firebaseConfig.js

const firebase = require('firebase/app'); require('firebase/auth') require('firebase/firestore') // config vừa tạo const firebaseConfig = { apiKey: "AIzaSy...", authDomain: "vicuatui.firebaseapp.com", databaseURL: "https://vicuatui.firebaseio.com", projectId: "vicuatui", ... } firebase.initializeApp(firebaseConfig); const db = firebase.firestore() const auth = firebase.auth() module.exports = exports = { db, auth, }

2. Sử dụng CFAuthProvider

App.js

import { auth, db } from "./firebaseConfig"; import { CFAuthContext, CFAuthProvider } from "./CFAuthProvider"; export default function App() { return ( <CFAuthProvider auth={auth} firestore={db} > <CFAuthContext.Consumer> { ({ loading }) => { if (loading) return 'Loading...' return ( 'Màn hình Login hoặc màn hình chính' ) } } </CFAuthContext.Consumer> </CFAuthProvider> ); }

Giải thích cơ chế:

Trong CFAuthProvider.js mình có:

  • useGlobal để lưu trữ biến dùng toàn cục (app) (tìm hiểu thêm trong ReactN)

  • useAuthState của react-firebase-hooks sẽ lắng nghe trạng thái login logout của người dùng

  • useDocument lắng nghe sự thay đổi dữ liệu của người dùng đó.

quy trình là useAuthState,useDocument > set vào biến user để sử dụng trong app.

return trong useUser để sử dụng trong <CFAuthContext.Consumer>

Chúc các bạn Thành Công 🖖