Search code examples
reactjsreact-nativesetstate

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


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())
          }

Solution

  • 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())
                    }