0

This question is somewhat related to this issue I had earlier today:

Adding items to an array in javascript

It works to add items to my array now, but it seems that when I update the array all items will be the same even though the object passed into the method is different everytime

My method looks like this:

addShoe(shoe) {
    console.log("Adding new shoe to collection: ");
    console.log(shoe);
    this.setState(
      {
        shoes: [...this.state.shoes, shoe]
      },
      function() {
        console.log("Shoe collection:");
        console.log(this.state.shoes);
      }
    );
  }

So after one run, this is what the console in Chrome looks like. Which seems to be right:

enter image description here

When I try to add one more to the collection, this is what happens:

enter image description here

Now my collection contains two items which is correct, but it seems like all items in the collection has the same data?

What am I doing wrong here? EDIT

In another React component I have the following state:

this.state = {
      shoe: {
        selectedBrand: "",
        selectedEU: "",
        selectedUS: "",
        selectedUK: "",
        selectedFraction: ""
      }
    };

Once a field is updated with a new value, the following method will be triggered:

 updateSelectedValues(property, event) {
    const shoe = this.state.shoe;
    shoe[property] = event.value;
    this.setState({ shoe: shoe });
  }

When a button in this modal window is closed, the this.state.shoe will be pass as a param to method in the "parent" component.

6
  • 6
    Sounds like shoe is same object reference in each element in array. Need more context where it comes from to be passed into addShoe() Commented Nov 14, 2018 at 14:13
  • Need to see the code that calls addShoe(); Commented Nov 14, 2018 at 14:16
  • Yep. It was the same object reference! Commented Nov 14, 2018 at 14:23
  • So knowing that do you still have problem resetting to new object? Commented Nov 14, 2018 at 14:48
  • 1
    could create function that returns a blank object ... function emptyShoe(){ return { selectedBrand: "", selectedEU: "", selectedUS: "", selectedUK: "", selectedFraction: "" }) and reset state setState({shoe:emptyShoe()}) Commented Nov 14, 2018 at 19:44

0

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.