简体   繁体   中英

initialize useState with data from firestore

I'm looking for a way in initialize a useState object with the value that is fetched from firestore

getDoc(docRef).then((doc) => {
    const initEmail = doc.data().email
    console.log(initEmail)
    return initEmail
})

const [email, setEmail] = useState(initEmail)

how would i go about doing this?

You should call the setter function for the state inside the asynchronous callback:

getDoc(docRef).then((doc) => {
    const initEmail = doc.data().email
    console.log(initEmail)
    setEmail(initEmail);
})

const [email, setEmail] = useState(initEmail, "initial value for email")

In case you want to do it as page loads, you should use useEffect,

useEffect(() => {
        getDoc(docRef).then((doc) => {
                const initEmail = doc.data().email
                console.log(initEmail)
                setEmail(initEmail);
        })
}, [])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM