Barry Michael Doyle
Barry Michael Doyle

Reputation: 10588

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!

Upvotes: 7

Views: 10462

Answers (1)

Andy Noelker
Andy Noelker

Reputation: 11269

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 (...)
}

Upvotes: 9

Related Questions