RGS
RGS

Reputation: 4253

parse data from firebase in react render

I'd like to parse data I receive from componentdidmount to render.

I have this state:

constructor(props) {
    super(props);
    this.state = {
        loading: true,
        data: []
    }
}

and this componentdidmount:

componentDidMount() {

    var post = [];

    var feedRef = firebase.database().ref().child('posts').limitToLast(10);
    feedRef.once('value', async (snapshot) => {

        post.push(
            Object.assign(snapshot.val(), {
                key: snapshot.key,
                user: snapshot.user,
                img: snapshot.img
            })
        )

        this.setState({ data: post, loading: false });

        console.log(this.state.data); // has the data

    });
}

and this to parse the data:

{this.state.data.map(post => {

                        return(
                            <div>
                                <img src={post.img} />
                            </div>
                        )

                    })}

The problem is, although I have data in state it is not being parse in render. Any ideas what is wrong?


I also have this error: index.js:1 Warning: Each child in a list should have a unique "key" prop.

my data is wrong: the console.log:

Array(1)
0:
-M7Y4RJMl1pd4ynwXPYJ: {img: "https://", user: "josh", userid: "T87u4DL82IaGO9X"}
-M7Y4RJMl1pdwXPYJ: {img: "https://", user: "josh2", userid: "T87u82IaGO9X"}
-M7Y4RXPYJ: {img: "https://", user: "josh3", userid: "T87u4DL82GO9X"}
-M7Y4RJMl1XPYJ: {img: "https://", user: "josh4", userid: "T87uaGO9X"}
img: undefined
key: "posts"
user: undefined

Upvotes: 0

Views: 179

Answers (1)

phoenixstudio
phoenixstudio

Reputation: 2598

check the docs https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html You need to convert the object into an array, the map function in the render is expecting an array, but you are using an object

var obj = snapshot.val();
var arrayPosts = Object.keys(obj).map(function(key) {
  return {
    key,
    user: obj[key].user,
    img: obj[key].img
 }
});
post = arrayPosts

Upvotes: 1

Related Questions