简体   繁体   中英

How to convert or map a Firebase Snapshot child into a custom object in React Native

I need to get data from Firebase Realtime & display within a FlatList.

What's the best way to capture the child value & map or convert it into my custom object?

Example:

class ObjectModel {

    constructor(id, name, age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
}

export default new ObjectModel();

// on my Screen.js file, getting the data...
useEffect(() => {
    reference
      .on('value', snapshot => {
        
        let data = [];
       
        snapshot.forEach((child) => {
          // I need to make the child.val() to be an ObjectModel
          data.push(child.val());
        })

        setArr(data);
      });
  });

Try spreading the val like this and then pushing it to your array:

let newObjModel = new ObjectModel ({...child.val()})

is this is what you were looking for?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM