0

A few different main components in my React app use functions to retrieve data from my Firebase database.

I put these as static functions in a helper class, as such:

class FirebaseRetrieveHelper extends Component {
    ... (other functions)

    // Gets all PDE files, for all users
    static getAllFromAllUsers = () => {
        this.usersCollectionRef.get().then(querySnapshot => {
            querySnapshot.forEach(doc => { 
                this.userCodeCollectionRef(doc.id).onSnapshot(querySnapshot => {
                    var items = querySnapshot.docs.map(function (documentSnapshot) {
                        data = documentSnapshot.data();
                    });
                });
            });
        });
        // I can't do this:
       return data
    }
}

I access these functions from another component as follows:

class TAView extends Component {

    constructor(props) {
        super(props);

        this.state = {
            items: [],
            ....
        }

    }

    componentWillMount() {
        var items = FirebaseRetrieveHelper.getAllFromAllUsers();
    }

...

The way fetching from Firebase works, I need to use a .then() function, and normally one would then retrieve its value by putting in in the state of the corresponding class, which would be the answer to the many similar questions on promise functions in React. This wouldn't work in this case, as this is a static function from a helper class.

How might I access the response from my .then() function? Or is there a much better, React-y way to tackle this problem?

Teresa
  • 353
  • 1
  • 5
  • 27
  • 2
    This isn't a React-specific thing. Since the functions get their data asynchronously, they can only *provide* that data asynchronously. You can't wrap an asynchronous process in a synchronous one. `getAllFromAllUsers` will need to return the promise chain, and then `componentWillMount` (or better, `componentDidMount`) will need to consume that promise. – T.J. Crowder Jun 23 '19 at 15:39
  • Returning the promise chain is a good answer I didn't think of, thanks. I will answer my own question then. – Teresa Jun 23 '19 at 15:43

0 Answers0