Reputation: 555
I'm a beginner with React, and I would like to add an object into an array.
Here is my code :
const initialState =
{
messages: [],
};
export default (state = initialState, action) => {
switch (action.type) {
case 'ADD_MESSAGE':
return {
messages: update(state.messages, {$push: [{text: action.text}]})
};
default:
return state
}
}
And in my component:
<ul>{this.props.chat.messages.map((message) =>{ return <li>{message.text}</Link></li> })
}
And I get the error:
Encountered two children with the same key,
[object Object]. Child keys must be unique; when two children share a key, only the first child will be used.
Thank you for your help.
Upvotes: 1
Views: 1115
Reputation: 841
By definition, Arrays are immutable data.
Following in the best practices, preferred use the $splice method.
Upvotes: 0
Reputation: 1018
You have to provide unique keys for each list item. Your messages don't have a key/ID and you need to provide a uniquely generated ID or as a last resort, use the index (which should be avoided as long as possible). The code above can be refactored as:
{ this.props.chat.messages.map((message, index) => (<li key={index}>{message.text}</li>) }
Upvotes: 4