Chris Chris - 5 months ago 15
JSON Question

Object appears to be empty inside of react render() even if previous logging proves that it's not

I have this component in my React app:

class ChannelList extends React.Component {
render() {
console.log("1. return: " + JSON.stringify(this.props.channels));
return (
<ul>
{this.props.channels.map(chan => {
console.log(JSON.stringify(chan));
return (
<Channel
key={chan.id}
channel={chan}
{...this.props} // Pass all properties
/>
)
})}
</ul>
)
}
}


The first log method reads like this:
1. return: [{"channel":{"id":1,"name":"asdf"}}]

The second log method like this:
{"channel":{"id":1,"name":"asdf"}}


But when running this code I get an error message, that each child should have a unique "key".
The problem appears to be that when I use
chan.id
the object is empty.
Since I logged it just three lines before proving it is not there must be some other issue with this. I am new to JavaScript in general and React in particular.

Is there something wrong with my syntax or the way I'm trying to access th
id
value?

Answer

Use chan.channel.id

class ChannelList extends React.Component {
    render() {
        console.log("1. return: " + JSON.stringify(this.props.channels));
        return (
            <ul>
                {this.props.channels.map(chan => {
                    console.log(JSON.stringify(chan));
                    return (
                        <Channel
                            key={chan.channel.id}
                            channel={chan}
                            {...this.props} // Pass all properties
                        />
                    )
                })}
            </ul>
        )
    }
}
Comments