Firebase是Alphabet(google)的子公司,提供了一些很好用的服務,例如,身分驗證、Firestore(NoSQL database)。

<aside> 📢 尙未完全改為SvelteKit語法

</aside>

需要import相關套件

import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword } from 'firebase/auth';
const auth = getAuth();
const res = await createUserWithEmailAndPassword(auth, account.email, account.password);
    message = "";//清除前次訊息
    try {
      const res = await createUserWithEmailAndPassword(
        auth,
        userID,
        password
      );
      message = "帳號已產生";
      console.log({ res });
    } catch (error) {
      switch (error.code) {
        case "auth/email-already-in-use":
          message = "電子信箱已註冊";
          break;
        case "auth/weak-password":
          message = "密碼強度不足";
          break;
        case "auth/invalid-email":
          message = "電子郵件格式錯誤";
          break;
        default:
          message = "系統錯誤:" + error.code;
      }
      
    }
      const auth = getAuth();
      const res = await signInWithEmailAndPassword(
        auth,
        userID,
        password
      );
    (user)=>{
      setCurrentUser(user);
      console.log(user);
    }
  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user)=>{
      setCurrentUser(user);
      console.log(user);
    });

    return () => {
      unsub();
    }
  }, []);

在介面中,判斷state變數currentUser是否為null,就知道現在是否已登入,透過這樣的方式來改變介面的呈現內容。