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

Jack23
  • 1,368
  • 7
  • 32

3 Answers3

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();
}
DEEPAK
  • 1,364
  • 10
  • 24
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.

a.deshpande012
  • 715
  • 7
  • 18
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

lizzmo
  • 201
  • 1
  • 13
  • I have tried to use `var newInput = this.state.inputs.length.pop() `, but I don't know how to save the state then.. – Jack23 Apr 16 '21 at 18:13
  • 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 – Jack23 Apr 16 '21 at 18:16