chackerian
chackerian

Reputation: 1401

How to set data in Firebase .onSnapshot()

I'm trying to set data with this function and its not setting the variable. How can I set information for outside use with this?

Here is my code

const docRef = store.collection('users').doc(item.email)
var image;
docRef.onSnapshot((doc) => {
    if (doc.exists) {
        image = doc.data().picture
    }
})

How can I set the image variable within this function to use outside the onSnapshot? This is a React JS project.

Upvotes: 1

Views: 450

Answers (1)

Salem_Raouf
Salem_Raouf

Reputation: 431

In react you should handle data in state

import React ,{useState} from 'react';

const [image,setImage] = useState('');
 const docRef = store.collection('users').doc(item.email);
 docRef.onSnapshot((doc) => {
     if (doc.exists) {
        setImage(doc.data().picture) // Set Image Here
     } })

now you can work with image const outside the onSnapshot scoop

Upvotes: 1

Related Questions