P粉0378809052023-08-27 12:25:17
要檢查使用者是否已登錄,您可以使用'onAuthStateChanged'方法。
將此資訊儲存在元件的狀態中,或使用它來有條件地渲染元件的部分。
import React, { useEffect, useState } from 'react'; import firebase from 'firebase/app'; import 'firebase/auth'; export default function Home() { const [user, setUser] = useState(null); useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { setUser(user); }); return () => unsubscribe(); }, []); return ( <main> <h1>Hello World</h1> {user ? ( <p>authenticated user</p> ) : null} </main> ); }
要在伺服器端執行使用者驗證,Next.js提供了'getServerSideProps'來取得使用者的驗證狀態
import firebase from 'firebase/app'; import 'firebase/auth'; export default function Home({ user }) { return ( <main> <h1>Hello World</h1> {user ? ( <p>authenticated user</p> ) : null} </main> ); } export async function getServerSideProps(context) { const user = await new Promise((resolve, reject) => { firebase.auth().onAuthStateChanged(user => { resolve(user); }); }); return { props: { user, }, }; }
更新的解決方案:
建立一個伺服器端路由
import firebase from 'firebase/app'; import 'firebase/auth'; import express from 'express'; const app = express(); app.get('/api/user', async (req, res) => { const user = await new Promise((resolve, reject) => { firebase.auth().onAuthStateChanged(user => { resolve(user); }); }); res.send(user); }); app.listen(3000, () => { console.log('Server started at http://localhost:3000'); });
客戶端程式碼
import React, { useState, useEffect } from 'react'; import axios from 'axios'; export default function Home() { const [user, setUser] = useState(null); useEffect(() => { const fetchUser = async () => { const res = await axios.get('http://localhost:3000/api/user'); const user = res.data; setUser(user); }; fetchUser(); }, []); return ( <main> <h1>Hello World</h1> {user ? ( <p>authenticated user</p> ) : null} </main> ); }