0

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
2
  • 1
    For the key issue it means that you have to add a unique key prop to each element. E.g. <div key={postUniqueKey}>. For the original issue culd you provide a CodeSandbox of this? Commented May 19, 2020 at 13:44
  • @radulle I edit my question with the array I get. I think it is wrong... maybe something I did wrong to push the array... Commented May 19, 2020 at 13:49

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.