1

I have a component AddMenu

constructor(props) {
  super(props);
  this.state = {
    menu: '',
    make: '',
    newCar: '',
  }  
  this.addConfirmFuction=this.addConfirmFuction.bind(this);
}

Make the menu, make, model, year updated by changing the input text, it works.

handleChangeEvent(e) {
    this.setState({
        [e.target.name]: e.target.value,
    });
  }

Then I want to combine everything in the state to "newcar" in the state

addConfirmFuction() {
let newEntered=[];
newEntered=newEntered.concat(this.state.menu);
newEntered=newEntered.concat(this.state.make);
this.setState({newCar:newEntered,});
}

After run the last line of code: this.setState (newCar: newEnteredCar), it is not updated, it is still ''. I looked at lots of documents and couldn't figure out...I have bind the function in the state constructor, I have used setState function, but couldn't update the state.thank you in advance.

Djib2011
  • 6,874
  • 5
  • 36
  • 41
H.Alex
  • 13
  • 5

1 Answers1

0

Did you check if the state values "make" and "menu" are really not empty inside "addConfirmFunction()"?

Also, from your code, it looks like "make" and "menu" are just strings. Any reason for "newCar" being set with a value of type array? If it need not to be array, then this.state.make + this.state.menu would suffice I guess!

Edit:

I think I got the problem. If you are checking the state value immediately after the line is called, then you might not see the new value there since setState is an async function in React. (For performance gains). Please read this stack overflow link. There are lots of article which talks about it.

If you want to see the new value, since this setState calls for a render, keep a breakpoint at render method and check if the value of newCar is available there.

VigSank
  • 62
  • 8
  • Thank you very much, Vicky, for your answer, yes, finally I got to see the value updated by your advice. – H.Alex Aug 21 '18 at 01:33