0

I'm really stuck with this issue, it looks very simple but I just cannot access childs of a parent Object, please someone assist. The picture below is the console log:

db

When I render this I don't see the results

const listItems = this.state.list.map((item, index) => <p>{item.title}</p>);

Of course when I try this.state.list.map((item, index) => <p>{item}</p>); I got the error bellow:

Objects are not valid as a React child

The main function:

componentDidMount = () => {
    fire
        .database()
        .ref(`/feed/`)
        .on('value', snapshot => {
            var obj = snapshot.val();
            var list = [];
            for (let a in obj) {
                list.push(obj[a]);
            }
            console.log(list);
            this.setState({
                list: list,
                loading: false
            });
        });
};

A live session can be found here (Home.js) https://codesandbox.io/live/DR7WzY

EDIT : my last attempt

        for (let a in obj) {
            for (let b in obj[a]) {
                console.log(b);
            }
        }

But it's empty!!

1 Answer 1

1

item.title works because it's a string. You can't pass an object, if you want to view the object then you can just stringify it:

this.state.list.map((item, index) => <p>{JSON.stringify(item)}</p>);

Since you have nested objects you would need to do something like:

this.state.list.map((item, index) =>
  Object.values(item).map(nestedItem => 
    <p>{JSON.stringify(nestedItem)}</p>));
Sign up to request clarification or add additional context in comments.

4 Comments

well that's a great suggestion now I got this in my view : {"-LOQ780BQvgYVkbLnkpE":{"description":"TEST","picture":"TEST","title":"TEST","user":"TEST"},"-LOQ7AWEEYVcjRQV-kDC":{"description":"TESTPOST","picture":"POST","title":"POST","user":"TEST"}}
Do you have no way of knowing the keys?
Definitely not, it's the uid of users @matt-aft
try what i posted above, it will grab the values of your nested objects

Your Answer

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