【问题标题】:Create a user document after creating a user in authentication in firebase在firebase中创建身份验证用户后创建用户文档
【发布时间】:2021-06-29 03:13:05
【问题描述】:

我正试图弄清楚在创建用户身份验证记录后如何在 Firestore 中创建用户文档。

我目前的尝试如下。

当我添加 async/await 时,代码会生成错误消息。当我删除它们时,身份验证部分会在 firebase 的身份验证部分创建用户记录,但不会创建 firestore 记录。不会生成错误消息。

谁能看出发生了什么问题?

import React, {useState} from 'react';
import { auth, firestore } from '../../../services/firebase/firebase';
import { useHistory } from 'react-router-dom';

import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import { Buttons } from '../navigation/styles';

export default function FormDialog() {
  const [open, setOpen] = React.useState(false);
  let [loading, setLoading] = useState(false);
  const history = useHistory();
  const [displayName, setDisplayName ] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState(null);



  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const handleSubmit = async (event) => {
    setLoading(true);  
        event.preventDefault();
        auth.createUserWithEmailAndPassword( email, password)

下面的尝试记录了 UID,但是说 TypeError: user.updateProfile 不是函数

.then((res) => {
            console.log("logging user", (auth.currentUser.uid) );
            const user = auth.currentUser.uid;
            return user.updateProfile({
                    displayName: displayName
                })
                firestore.collection('users').doc(auth.currentUser.uid)
                .set({
                    fullName: displayName,
                    createdAt: firestore.fieldValue.serverTimestamp(),
                })
            })

    

这是另一种尝试,ASLO 无法吸引用户 Firestore 中的文档

.then(() => {
            if (auth.currentUser != null) {
                auth.currentUser.updateProfile({
                    displayName: displayName
                })
                firestore.collection('users').doc(auth.currentUser.uid)
                .set({
                    fullName: displayName,
                    createdAt: firestore.fieldValue.serverTimestamp(),
                })
            }
 

     })

//这是另一种尝试,可以替代上述方法,这也是 不工作

.then((res) => {
            const user = auth.currentUser;
            return user.updateProfile({
                    displayName: displayName
                })
                firestore.collection('users').doc(auth.currentUser.uid)
                .set({
                    fullName: displayName,
                    createdAt: firestore.fieldValue.serverTimestamp(),
                })
            })
        
       
    .then(() => {
        history.push("/");
     })
    .catch(error => {
        console.error(error);
    })
    .then(() => {
        clear();
    }) 
    .then(() => {
       handleClose() 
    })
    .finally(() => {
        setLoading(false);
    });
    
  };

这是进一步的尝试,我无法对其进行测试,因为关于尝试推送历史记录的 then 语句的某些内容被认为存在解析错误。我找不到任何关于如何解决这些问题的教程。

  const createUserDocument = async (user, displayName) => {
    if (!user) return;
  
    const userRef = firestore.doc(`users/${user.uid}`);
  
    const snapshot = await userRef.get();
  
    if (!snapshot.exists) {
      const { email } = user;
      const { displayName } = displayName;
  
      try {
        await userRef.set({
          displayName,
          email,
          createdAt: new Date(),
        });
      } catch (error) {
        console.log('Error in creating user', error);
      }
    }
  };

  const handleSubmit = async (event) => {
    setLoading(true);  
        event.preventDefault();
        try {
            const { user } = await auth.createUserWithEmailAndPassword(
              email,
              password
            );
            await createUserDocument(user, { displayName });
            } catch (error) {
            console.log('error', error);
            }
            
        .then(() => {
            history.push("/");
        })
        .then(() => {
            clear();
        }) 
        .then(() => {
        handleClose() 
        })
        .finally(() => {
            setLoading(false);
        });
        
    };

//continuing after all current attempts
  const onChangeHandler = event => {
    const { name, value } = event.currentTarget;
    if (name === "userEmail") {
      setEmail(value);
    } else if (name === "userPassword") {
      setPassword(value);
    } else if (name === "displayName") {
      setDisplayName(value);
    }
  };
  
  const clear = () => {
    setDisplayName("");
    setEmail("");
    setPassword("");
  };
  

  return (
    <div>
      <Buttons onClick={handleClickOpen}>
        Join
      </Buttons>
      <Dialog open={open} onClose={handleClose} aria-labelledby="form-dialog-title">
        <DialogTitle id="form-dialog-title">Join the waitlist</DialogTitle>
        <DialogContent>
          <DialogContentText>
            Join
          </DialogContentText>
          <TextField
            autoFocus
            margin="dense"
            label="Full name"
            type="text"
            fullWidth
            name="displayName"
            value={displayName}
            placeholder="Jill Green"
            id="displayName"
            onChange={event => onChangeHandler(event)}
          />
          
          <TextField
            
            margin="dense"
            label="Email Address"
            type="email"
            fullWidth
            name="userEmail"
            value={email}
            placeholder="email address"
            id="userEmail"
            onChange={event => onChangeHandler(event)}
          />
          <TextField
            
            margin="dense"
            label="Password"
            type="password"
            fullWidth
            name="userPassword"
            value={password}
            id="userPassword"
            placeholder="Minimum 6 characters"
            onChange={event => onChangeHandler(event)}
          />
          
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose} color="primary">
            Cancel
          </Button>
          <Button 
            onClick={handleSubmit} 
            color="primary">
            Register
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore


    【解决方案1】:

    除了试图弄清楚如何在 firebase 中记录时间戳的持续问题之外,这还可以创建用户文档记录。

    const handleSubmit = async (event) => {
        setLoading(true);  
            event.preventDefault();
            auth.createUserWithEmailAndPassword(
                email,
                password
            )
            .then(credential => {
                if (credential && credential.user) {
                  firestore.collection("users")
                    .doc(credential.user.uid)
                    .set({
                      email: email,
                      displayName: displayName,
                    //   createdAt: firestore.Timestamp.now()
                        // createdAt: firestore.fieldValue.serverTimestamp()
                        // createdAt: firebase.firestore.fieldValue.serverTimestamp()
                        
                    });
          
                  history.push("/");
                }
            })
      
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      相关资源
      最近更新 更多