![](/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.