![](/img/trans.png)
[英]fetched data from firestore as initial value of useState it gives me udefined value
[英]I want to set the fetched data from firestore as initial value of useState
我想将从 firestore 中获取的数据设置为 useState 的初始值,但它给了我未定义的值,因为我想编辑用户配置文件并且我不确定用户编辑哪个属性我想让其他属性保持不变
import React, { useState, useEffect } from 'react';
import { useAuthState } from 'react-firebase-hooks/auth';
import { doc, onSnapshot } from "firebase/firestore";
import { auth, db } from '../../firebase';
export default function Form({ setEditForm }) {
const [user, setUser] = useState([]);
const [currentUser] = useAuthState(auth);
// fetching user information from firestore
useEffect(() => {
const getUser = async () => {
const docRef = doc(db, 'users', currentUser.uid)
await onSnapshot(docRef, (doc) => {
setUser({
...doc.data(), id: doc.id
})
})
}
getUser()
}, [])
const [name, setName] = useState(user.firstName);
const [surname, setSurname] = useState(user.surname);
const [biograhpy, setBiography] = useState(user.biograhpy);
const [location, setLocation] = useState(user.location);
// the name is undefined why? I want to put the fetching data from firestore as initial value of use state but it's undefined
console.log(`name ${name}`)
);
}
我不确定,但我认为你应该这样做:
const [user, setUser] = useState([]);
const [currentUser] = useAuthState(auth);
const [name, setName] = useState();
const [surname, setSurname] = useState();
const [biograhpy, setBiography] = useState();
const [location, setLocation] = useState();
const getUser = async () => {
const docRef = doc(db, 'users', currentUser.uid)
try {
await onSnapshot(docRef, (doc) => {
setUser({
...doc.data(), id: doc.id
})
})
setName(user.firstName)
setSurname(user.surname)
setBiography(user.biograhpy)
setLocation(user.location)
} catch (e) {
console.log(e)
}
}
// fetching user information from firestore
useEffect(() => {
getUser();
}, [])
console.log(`name ${name}`)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.