0

I am working on my react-app and I am now using react-redux-firebase. Following the step. I want to make it synchronize and use setState() method.

It shows the error:

TypeError: Cannot read property 'then' of undefined

dbGetDate.js

const dbGetData = (store, col, doc, col2, doc2) => {
    store.firestore.collection(col).doc(doc).collection(col2).doc(doc2).get().then(data => {
            if (data.exists) {
                return new Promise((resolve, reject) => {
                    if(data.data() != null){
                        resolve(data.data());
                    }
                else{
                    reject("Some error in fetching data");
                }

            })

        }
        else {
            return new Promise((resolve, reject) => {
                reject("not such data in record");
            })
        }
        }
    ).catch(function (error) {
        return ("Ops, there should be an error");
    });
}
export default dbGetData;

myPage.js

componentWillMount(){
        const dbStore = dbConnect;
        dbGetData(dbStore, 'Test', '123', 'Member','001')
        .then(data => {
            console.log(data);
            this.setState({
                firebaseData : data
            })
        });

}

1 Answers1

1

The reason you're getting that error is because the function dbGetData doesn't return anything, therefore the result of calling it is undefined. If you want it to return a Promise you'll have to create the Promise at the top level:

 const dbGetData = (store, col, doc, col2, doc2) => {
   const promise = new Promise((resolve, reject) => {
     // ... do stuff
   });

   return promise;
 };
Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44
  • it works! but can I return promise in the if else block without creating promise variable on top of the function? – MoMo WongHK Dec 30 '18 at 10:17
  • You can't because if the `if / else` lives inside a callback so you wouldn't be able to return the promise in the top level function. Also, I can't see any reason why you would want that in your snippet. – Daniel Conde Marin Dec 30 '18 at 10:19