1

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.

2 Answers 2

4

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>) }
Sign up to request clarification or add additional context in comments.

Comments

0

By definition, Arrays are immutable data.

Following in the best practices, preferred use the $splice method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.