Skip to content Skip to sidebar Skip to footer

Add Object To Array JS

I cannot add new object to array. Why? var messagesArray = [ {message: 'Hello', style: styles.nikkiMes}, {message: 'Okkkk', style: styles.userMes} ]; this.state = { messag

Solution 1:

As suggested by @Sam Onela in comment above, you don't have messagesArray key within state object or messagesArray is not a property of state object, also try to avoid to use push, that is a mutating function instead try concat and spread operator.You can try following solutions to overcome the issue

1)

 var messagesArray = [
  {message: "Hello", style: styles.nikkiMes},
  {message: "Okkkk", style: styles.userMes}
];

this.state = {
  messagesSource: ds.cloneWithRows(messagesArray.slice()),
  inputMes: ''
};
//these lines of code will not be needed if you are using spread operator
messagesArray.concat({             //replaced push with concat, meassageArray is a global object
  message: this.inputMes,
  style: styles.userMes
});

this.setState({
  messagesSource: ds.cloneWithRows(messagesArray.slice())
  //messagesSource: ds.cloneWithRows([...messageArray, {message: this.inputMes,style: styles.userMes}])  // see how you can directly use spread operator
});

2)

var messagesArray = [
  {message: "Hello", style: styles.nikkiMes},
  {message: "Okkkk", style: styles.userMes}
];

this.state = {
  messagesSource: ds.cloneWithRows(messagesArray.slice()),
  inputMes: '',
  messagesArray :messagesArray //I included messagesArray  within state
};


this.setState((prevState, props)=>{
 messageArray:[...prevState.messageArray, {message: this.inputMes,style: styles.userMes}]
})

this.setState({
  messagesSource: ds.cloneWithRows(this.state.messagesArray) //first solution will be most fit for your case as messageArray would not have been updated till now
});

Solution 2:

You have a simple typo. You have set the array at state.messagesSource and are trying to add to state.messagesArray which doesn't exist. There is a messagesArray variable but not one available on the state.


Post a Comment for "Add Object To Array JS"