ChristianLLM
ChristianLLM

Reputation: 1

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?

Upvotes: 0

Views: 294

Answers (2)

Hrushikesh Malshikare
Hrushikesh Malshikare

Reputation: 36

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);
        })
}, [])

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

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")

Upvotes: 1

Related Questions