2

I want to get the updated values of an array. When I do a console.log I only get the length of the array and the new values aren't shown in the view. What is wrong here? js fiddle

react js

getInitialState: function() {
  return {
    owner: "Martin Schwatz",
    friends:  ["Pietro", "Mike", "Shawn", "Bilbo"],
  }
},
updateFriends: function(friend) {
  var a = this.state.friends.push(friend);
  console.log(a);
  this.setState({
    friends: a,
  });
},
2
  • @DavinTryon, but how would a react developer get the new values into the array? Commented Nov 17, 2016 at 12:02
  • push returns the length of the array. Commented Nov 17, 2016 at 12:04

2 Answers 2

2

Take a look at this one

var Hello = React.createClass({
  getInitialState: function() {
    return {
      owner: "Martin Schwatz",
      friends:  ["Pietro", "Mike", "Shawn", "Bilbo"],
    }
  },
  updateFriends: function(friend) {
    var newFriends = this.state.friends.concat(friend)
    this.setState({
      friends: newFriends,
    });
  },
  click: function(){
    this.updateFriends('VuVu')
  },
  render: function(){
    var listOfFriends = this.state.friends.map(function(item,i){
        return <li key={i}>{item}</li>
    }.bind(this))
    return <div>
        <button onClick={this.click}>Add VuVu</button>
        <hr/>
      {listOfFriends}
    </div>
  }
});

ReactDOM.render(
  <Hello />,
  document.getElementById('container')
);

It should work for you <fiddle>

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

Comments

1

push returns the new length of the mutated array. So, in the current code, a won't be the array itself.

Try this instead:

updateFriends: function(friend) {
  const newFriends = [ ...this.state.friends, friend ];
  this.setState({
    friends: newFriends,
  });
},

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.