3

I'm currently starting to learn ReactJS and have run into some trouble updating an array.

Currently I have a searchable list of contacts which is working fine. But using the input box below the list I am trying to add additional items to the list using the update() function.

Sample of what I've got so far for the update function is below. Ideally at some point the updated content would come from the input box to the left of the button, but currently I'm just trying to push a static item as a test.

  updateContact: function(e){
    e.preventDefault();
    var newItems = React.addons.update(this.state.initialItems, {$push: ["New Item"]})
    return;
  },

Any help or direction would be greatly appreciated, and a full JSFiddle with the entire code can be found below.

JS Fiddle

1
  • What exactly is the issue you are having? Does something not work as expected? What is it and what do you expect? Commented Jun 11, 2015 at 16:14

1 Answer 1

3

You are not calling setState, so the component never re-renders:

updateContact: function(e){
  e.preventDefault():
  var newItems = React.addons.update(this.state.initialItems, {$push: ["New Item"]});

  this.setState({
    initialItems: newItems,
    items: newItems
  }); // update state
},

Note that update both, this.state.items, this.state.initialItems. I assume you are using items for the filtered list and initialItems for all items in the list.

Of course you have to replace "New Item" with the actual value of the text field.


I would also remove componentWillMount and simply set initialItems and items to the same value in getInitialState.

Also if you'd simply bind the handler directly to the button and remove the <form>, you don't have to deal with preventing the event. It seems a rather roundabout way to trigger the callback.

Cleaned up example: https://jsfiddle.net/f554xrh0/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Can't believe I was missing something as simple as just updating the state. As for the initialItems vs items, I had followed a tutorial to set that part up and wasn't sure either, I appreciate the guidance on that too.

Your Answer

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