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!
The "TypeError: map is not a function" occurs when we call the map() method on an object that is not an array. To solve the error, console. log the value you're calling the map() method on and make sure to only call the map method on valid arrays.
In React, the map method is used to traverse and display a list of similar objects of a component. A map is not a feature of React. Instead, it is the standard JavaScript function that could be called on an array. The map() method creates a new array by calling a provided function on every element in the calling array.
The React. js "Uncaught TypeError: X is not a function" occurs when we try to call a value that is not a function as a function, e.g. calling the props object instead of a function. To solve the error, console. log the value you are calling and make sure it is a function. Here is an example of how the error occurs.
To map through an object's value in React:Use the Object. values() method to get an array of the object's values. Call the map() method on the array of values.
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 (...)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With