Jatin Garg
Jatin Garg

Reputation: 344

Firestore React-Native not fetching Data

Need to integrate Firebase and Firestore both in React native app, Successfully able to use Firebase and it's real-time DB but not able to use firestore. Returning Empty Data in console.

Npm package: npm install --save firebase

Firebase Reference

import * as firebase from 'firebase';

const config = {
    apiKey: "xxxx",
    authDomain: "xxx.firebaseapp.com",
    databaseURL: "https://xxxx.firebaseio.com",
    projectId: "xxxx",
    storageBucket: "xxx.appspot.com",
    messagingSenderId: "xxx",
    appId: "xxxx:web:xxxx",
    measurementId: "xxx"
  };

  const Firebase = firebase.initializeApp(config);
   
  export default Firebase;

Table References:

import {
    Firebase
} from '../firebase'

export const userTableReference = Firebase.database().ref('users') -> Working
export const healthTipReferences = Firebase.firestore().collection('HealthTips') -> Not working

Fetching Values

export function getHealthTips() {
    return async (dispatch) => {
        try {
            healthTipReferences.onSnapshot(querySnapshot => {
                querySnapshot.forEach(doc => {
                    if (doc.exists) {
                        console.log(doc.data())
                    } else {
                        console.log('no doc')
                    }
                });
            })
        } catch (error) {
            console.log("*** Firebase - error setting document", { error })
        }
    }
}

Response:

[Sun Oct 18 2020 14:50:29.757]  LOG      {}
[Sun Oct 18 2020 14:50:29.758]  LOG      {}
[Sun Oct 18 2020 14:50:29.758]  LOG      {}

FireStore Rules

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

Database Structure:

enter image description here

Upvotes: 0

Views: 267

Answers (1)

Jatin Garg
Jatin Garg

Reputation: 344

There was issue I created three level hierarchy of database values instead of one So, based on my hierarchy I need to modify my query.

Collection -> id
fields -> doc.Data()

below query I wrote to get data:

const healthTipsRef = await healthTipReferences.get();
            healthTipsRef.forEach(categories => {
                categories.ref.collection('Tips').onSnapshot(querySnapshot => {
                    querySnapshot.forEach(doc => {
                        finalData[categories.id] = doc.data()
                    })
                    console.log(finalData)
                })
            }) 

Upvotes: 1

Related Questions