I want to set the fetched data from firestore as initial value of useState but it gives me undefined value because I want to edit user profile and I'm not sure user edit which property I wanted to stay the other properties the same
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}`)
);
}
I`m not sure, but I think you should do smth like this:
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}`)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.