在 firebase 中的身份验证中创建用户后创建用户文档

时间:2021-04-02 07:49:14

标签: reactjs firebase google-cloud-firestore

我想弄清楚如何在创建用户身份验证记录后在 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 无法使用户 FIRRESTORE 中的文档

.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>
  );
}

1 个答案:

答案 0 :(得分:0)

除了试图找出如何在 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("/");
            }
        })