0

I want to push (splice) object from variable into array, but it causes an infinite loop, the point is to replace object in array with another object from React state.

handleDuplicate = (id, nextId) => {
  let items = [...this.state.items];
  let currentItem = this.state.items[id];
  if (items && currentItem) {
    console.log(currentItem); // --- logs object from react state properly
    for (var i = 0; i < items.length; i++) {
      if (items[i].id == nextId) {
        items.splice(i, 1);
        // items.splice(i, 0, currentItem); // --- causes infinte loop
        items.splice(i, 0, { id: 111, test: "test" }); // --- runs ok
        i--;
        console.log(items);
      } else {
        console.log("---");
      }
    }
  }
  this.setState({ items });
};

1 Answer 1

3

You can use the map function to replace the item :

handleDuplicate = (id, nextId) => {
  const currentItem = this.state.items[id];
  const items = this.state.items.map(
    item => item.id === nextId ? currentItem : item
  );

  this.setState(prevState => ({items});
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is it, thanks. Just modyfied a little. handleDuplicate = (id, nextId) => { const currentItem = this.state.items[id]; const items = this.state.items.map( item => item.id === nextId+1 ? currentItem : item, ); this.setState({items}); }

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.