1

I'm trying to delete elements of array using splice of incoming index.

handleClick(index) {
    const array = ['el1', 'el2', 'el3', 'el4'];   
    array.splice(index, 1);
    this.setState({ data: array });          
}

It works just fine but the result is that every time I fire handleClick in order to delete multiple elements I'm starting from the same point of const array. What I need to do is somehow save the array first without one element and when another handleClick is fired it'll work on smaller array, i.e. containing only three elements and making only 2 elements etc. How can I achieve that? Thank you

1
  • 1
    Store the array in state not in a variable inside the click handler. Then you only have one instance of it Commented Aug 10, 2018 at 22:14

1 Answer 1

1

You could keep your data array in the component state, and in your handleClick method use setState with a new array that is a copy of data that has had the element with index index removed.

You could get your data from the backend in componentDidMount and put it in state when the request is complete.

Example

function getData() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(["el1", "el2", "el3", "el4"]);
    }, 1000);
  });
}

class App extends React.Component {
  state = { data: [] };

  componentDidMount() {
    getData().then(data => {
      this.setState({ data });
    });
  }

  handleClick(index) {
    this.setState(prevState => {
      const data = [...prevState.data];

      data.splice(index, 1);

      return { data };
    });
  }

  render() {
    return (
      <div>
        {this.state.data.map((el, index) => (
          <button key={el} onClick={() => this.handleClick(index)}>
            {el}
          </button>
        ))}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

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

1 Comment

I forgot to mention that my array comes from a backend server so it cannot be yet used inside the constructor lifecycle. Sorry for that...

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.