Barry Michael Doyle Barry Michael Doyle - 1 month ago 11
React JSX Question

React Uncaught TypeError: this.state.messages.map is not a function

I'm developing a React application and I've run into a problem with this mapping function:

render() {
const messages = this.state.messages.map((message) => {
return (
<li key={message[".key"]}>{message.text}</li>
)
})
return (...)
}


I get the following error:


Uncaught TypeError: this.state.messages.map is not a function


I think it has something to do with the key. My messages state is filled using the
componentDidMount
function with
Firebase
:

componentDidMount() {
firebase.database().ref("messages/").on("value", (snapshot) => {
const messages = snapshot.val()
if(messages != null) {
this.setState({
messages: messages
})
}
})
}


And messages are added with this function:

submitMessage(e) {
const nextMessage = firebase.database().ref("messages/").push({
text: this.state.message
})
}


This means my Firebase database with one message looks like this:

{
"messages" : {
"-KV6trWbEW73p8oS49Qk" : {
"text" : "test"
}
}
}


My suspicion is that I am identifying the key incorrectly. Any help with solving this issue would be much appreciated!

Answer

The problem is that the response from the database is an object with keys, whereas map() needs to be called on an array. The easiest way to loop through an object is to use Object.keys() and then use bracket notation to access the values.

render() {
    const messages = Object.keys(this.state.messages).map((key) => {
        return (
            <li key={key}>{this.state.messages[key].text}</li>
        )
    })
    return (...)
}
Comments