Authentication

更新profile

Authentication也可以儲存一些使用者的資訊

我們來嘗試利用displayName儲存姓名

改一下SignUp.js,因為會使用到updateProfile,先新增import

import { updateProfile } from "firebase/auth";

為了能儲存displayName,改一下useState()

  const [account, setAccount] = useState({
    email: "",
    password: "",
    **displayName: ""**
  });

增加一個欄位來輸入displayName

return (
    <>
      **<TextField
        type="text"
        name="displayName"
        value={account.displayName}
        placeholder="姓名"
        label="姓名:"
        onChange={handleChange}
      />
      <br />**
      <TextField
        type="email"
        name="email"
        value={account.email}
        placeholder="電子郵件信箱"
        label="電子郵件信箱:"
        onChange={handleChange}
      />
      <br />
      <TextField
        type="password"
        name="password"
        value={account.password}
        placeholder="密碼"
        label="密碼:"
        onChange={handleChange}
        autoComplete="current-password"
      />
      <br />
      {message}
      <br />
      <Button variant="contained" color="primary" onClick={handleSubmit}>
        註冊
      </Button>
    </>
  );

在新增使用者之後(呼叫createUserWithEmailAndPassword()後),就可以利用updateProfile()儲存displayName

      const res = await createUserWithEmailAndPassword(
        auth,
        account.email,
        account.password
      );
      setMessage("帳號已產生");
      await **updateProfile(auth.currentUser, {
        displayName: account.displayName
      });**

取得profile

看一下如何取的profile裡的資訊,SignIn.js也改一下:

      const res = await signInWithEmailAndPassword(
        auth,
        account.email,
        account.password
      );
      **const user = auth.currentUser;**
      **const displayName = user !== null ? user.displayName : "";**

      setMessage(**displayName** + "已成功登入");

Untitled

firestore新增資料

不過,通常可能會想幫使用者儲存一些Authentication沒有支援的資訊,這時候,我們可以利用firestore來儲存這些資訊。