0

I have in my state:

this.state = { inputs: ['0'] } 

In my render :

   {this.state.inputs.map((input, i) =>     <Travel formName={FORM_NAME} number={input}/>)}
    <button onClick={ () => this.appendInput() }> CLICK ME TO ADD AN INPUT   </button>
    <button onClick={ () => this.deleteInput() }>  Delete   </button>

Now when I click on this.appendInput() I add a field like this:

  appendInput() {
    var newInput = `${this.state.inputs.length}`;
    console.log("`${this.state.inputs.length}`" , `${this.state.inputs.length}`)
    this.setState(prevState => ({ inputs: prevState.inputs.concat([newInput]) }));
    console.log("this.state.inputs add ", this.state.inputs)
    this.forceUpdate();
}

But I don't understand how can I do with the deleteInput, how can I delete the last field in this way?

EDIT: I have tried like this:

deleteInput(){
  var newInput = this.state.inputs.pop();
  this.setState( ({ inputs: newInput }));
  this.forceUpdate();
}

but then I receive the message:

_this.state.inputs.map

1
  • .pop() doesn't return the new array, it returns the popped item. Commented Apr 16, 2021 at 18:24

3 Answers 3

1

write your delete function like this, you were assigning popped data from the array.

deleteInput(){
  var newInput = [...this.state.inputs];
  newInput.pop();
  this.setState( ({ inputs: newInput }));
  this.forceUpdate();
}
Sign up to request clarification or add additional context in comments.

Comments

1

pop() will return the removed element, which you don't want to set your state as. Doing this will set your state to the single element that was just removed. This is what causes your error, as you're trying to call map() on an object which is not a list.

Instead, your deleteInput() should do this:

this.setState(state => state.inputs.slice(0,-1))

This will properly remove the last element of your inputs array from your state.

Additionally, as a side note, calling setState() automatically queues a rerender, so calling this.forceUpdate() is unnecessary and inefficient.

Comments

0

You should be able to use .pop() to remove the last item in your inputs array

This thread has some more detailed answers about pop and slice: Remove last item from array

2 Comments

I have tried to use var newInput = this.state.inputs.length.pop() , but I don't know how to save the state then..
I would do delete only the last number that I add, but as you can see in my edited post i receive an error when save the state

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.