hanuruh
hanuruh

Reputation: 260

Can't change state of string in React

I'm making a calculator and has i click on the numbers and operators i concat them in the display state.

class Calculator extends React.Component{ 
  constructor(props){
    super(props);
    this.state = {
      display:"",
      isLastDecimal:false,
      lastInput:''
    };
  }

I can't have two operators together, so if the last input was a operator and the new input is also an operator, i'll substitute the old one with the new one. I'm using pop() to remove the last digit and concact the new operator.
This doesn't apply to the '-' operator.
The function does enter in the condition of finding out that i'm having two operators together.

addToInput = val => {
    //decimal checking
    if(isNaN(val) && val!='.')
      this.setState({
        isLastDecimal:false
       });
    //change the initial state of 0 to the new display
    if(this.state.display=='0')
      this.state.display="";
    //can't have two '.' in a number
    if(this.state.isLastDecimal==false || val!='.'){
      //decimal checking
      if(val=='.')
        this.setState({
          isLastDecimal:true
        });
      //last operator is the chosen one (excluding '-')
      if(isNaN(this.state.lastInput) && isNaN(val) && hasPriority(this.state.lastInput) && hasPriority(val) ){
        //the problem is here!
        this.setState({
          display:this.state.display.pop() + val,
          lastInput:val
        });
      }else{
        this.setState({
          display:this.state.display + val,
          lastInput:val
        });
      }
    }
    console.log(this.state.display + val);
  }

I've also tried to save the new changed string inside a variable 'newDisplay' and change the state of display:newDisplay, but it also doesn't work. The rest of the code and conditions are working well and i don't think they are interfering.
Codepen: https://codepen.io/hanuruh/pen/dyPxRN

Upvotes: 0

Views: 677

Answers (1)

Roy Wang
Roy Wang

Reputation: 11260

String has no method .pop() so this.state.display.pop() would result in an error.

You can use this.state.display.slice(0, -1) instead to return the substring with the last character removed.

Upvotes: 1

Related Questions