Home > Blockchain >  Trying to update the values of an object in a state where the values are dependent on each other
Trying to update the values of an object in a state where the values are dependent on each other

Time:03-02

I am trying to update the values of an object in my state before I pass them into an API, But the calculation of values are dependent on each other. For e.g. if endTime takes current time and startTime takes the time before 10 minutes, on clicking a button endTime should get updated with startTime and startTime should take the time before 10 minutes. The problem I am facing is I set the endTime and when I am trying to set the startTime my endTime gets reset with the startTime. Is there any way of preserving the value of ObjValue1 ?

For example, if my endTime is 12:00pm and startTime is 11:50pm then onClick, my startTime should be 11:40pm and endTime should be 11:50pm

onClick(){
            let time = {...this.state.timeData};
            let option;
            option = this.state.dropdownOption;
            if(option === '10 minutes'){
            time['endTime'] =timeData['startTime'];
            console.log('endTime', timeData['endTime'])

            time['startTime'] = timeData['endTime'].subtract(10, 'm');
            console.log('startTime', time['startTime'])

            this.setState({timeData: time}, this.callAPI())
          }

CodePudding user response:

Ok, what you can do is stringify your times before setting your object, have a look below:

onClick() {
  const time = {
    ...this.state.timeData
  };
  const option = this.state.dropdownOption;
  if (option === '10 minutes') {
    
    // Let's get string versions of the times you need
    const newStartTime = JSON.stringify(time['endTime'].subtract(10, 'm'));
    const newEndTime = JSON.stringify(time['startTime']);
    
    // Set the new values in your time object
    time.startTime = newStartTime;
    time.endTime = newEndTime;

    // Now you can set the state
    this.setState({
        timeData: time
    }, this.callAPI())
  }
}

CodePudding user response:

Adding substract to both and removing the assignment operator helped me.

if(option === '10 minutes'){
                    timeData['startTime'].subtract(10, 'm');
                    timeData['endTime'].subtract(10, 'm');
                    this.setState({timeData: time}, this.callAPI())
                }
  • Related