johanjohansson
johanjohansson

Reputation: 541

How do I loop all Firebase children in React Native?

ANSWER AT BOTTOM OF POST (ALSO SEE @soutot ANSWER)

I have successfully gained text output from my Firebase code and so I know it works. Now I need to loop all the children in Firebase. Coming from swift, the way to do it is to store each item on a tempObject then append that to an array. Then you can simply use that array any way you like. This doesn't seem to work with JavaScript, or I'm doing something wrong. The fully functional FB code I now have is:

componentDidMount(){
    let child = "" 
    var ref = firebase.database().ref("testCategory");

    ref.once("value")
    .then(function(snapshot) {
        child = snapshot.child("test1/testHeader").val() 
        this.setState( {    
            child
        })
    }.bind(this)); 
}

I can then successfully print this in console or in <Text>. Now, the problem I'm having is looping all children, adding them to an array, then using that array to display the data. In my head, this is how it should work:

componentDidMount(){
    let child = "" 
    var ref = firebase.database().ref("testCategory");

    ref.once("value")
    .then(function(snapshot) {
        snapshot.forEach(function(childSnapshot){
           let tempObject = MyFirebase
           tempObject.testHeader = 
           childSnapshot.val() 

           myArray.append(tempObject) //or .push???
        })
        this.setState( {    //PASSING VARIABLE TO STATE
            child   
        })
    }.bind(this)); //BINDING TO SET STATE
}

I know that this is obviously wrong. Creating an object like that doesn't even work... MyFirebase -class looks like this:

render() {
let testHeader = ""
let testText = ""   
)
}

My Firebase database looks like this: FB DB (I ignored subText for now)

All suggestions are much appreciated :)

WORING CODE

 //FIREBASE CODE 
componentDidMount(){
    const ref = firebase.database().ref("testCategory");

    ref.once("value")
    .then(function(snapshot) {
        const categories = []

        //LOOPING EACH CHILD AND PUSHING TO ARRAY
        snapshot.forEach(item => {

            const temp = item.val();
            categories.push(temp);
            return false;
        });

        this.setState( {    //PASSING VARIABLE TO STATE
            child,
            categories
        })
    }.bind(this)); //BINDING TO SET STATE
}

Upvotes: 0

Views: 4512

Answers (1)

soutot
soutot

Reputation: 3671

According to the code you provided, it looks like it works until this point

var ref = firebase.database().ref("testCategory");

    ref.once("value")
    .then(function(snapshot) {

Am I correct?

From this point, if you add a console.log(snapshot.val()) it might print an array of objects, something like this: [ { test1: { testHeader: 'FirstHeader', testText: 'FirstText' } }, { test2: { testHeader: 'SecondSub', testText: 'SecondSub } }]

Right?

If so, you can for example store this snapshot into your state and then consume this state in your render method. Something like this:

const ref = firebase.database().ref('testCategory');

ref.once('value').then((snapshot) => {
  this.setState({ categories: snapshot.val() });
});

Then in your render method:

const { categories } = this.state;

categories.map(category => <Text>{category.testHeader}</Text>)

The result in your screen should be: FirstHeader SecondSub

Let me know if this helped

Some links that might explain more about es6 codes I used in this example:

array map categories.map(...): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

object destructuring const { categories } = this.state: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

const instead of var const ref = ...: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

setState: https://reactjs.org/docs/state-and-lifecycle.html

arrow function (snapshot) => ...: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Some about firebase snapshots: https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot

Hope it helps

Upvotes: 2

Related Questions