0

How to change the values of a object in the array in the react state by using setState?

My react state:

this.state = {
    serviceFees: [
        {
        periodFrom: new Date(),
        periodTo: new Date(new Date().getTime() + 24 * 60 * 60 * 1000),
        serviceFeeType: 'percentage',
        serviceFee: '',
        refundableStatus: 'refundable'
        }
    ]
};

And some of my onChange fuctions:

handlePeriodFromDateChange = (date) => {
    this.setState({
        periodFrom: date,
        periodTo: new Date(date.getTime() + 24 * 60 * 60 * 1000)
    });
}

handleRefundableStatus = (e) => {
    this.setState({
        refundableStatus: e.target.value
    })
}

handleChange = (e) => {
    this.setState({
        [e.target.name]: e.target.value
    })
}

1 Answer 1

1

Here you are doing it wrong. You can't directly write the properties name and value, without telling which index you want to update.

If you want to update the object property of lets say first index of the array then you have to do in like :

handlePeriodFromDateChange = (date) => {
    consr 
    this.setState({
       serviceFees: this.state.serviceFees.map((e,i)=>{
          if(i === 0) {
            return {
              ...e, 
              periodFrom: date,
              periodTo: new Date(date.getTime() + 24 * 60 * 60 * 1000)
            }
          }
          return e;
       }})
    });
}

You have to change the reference of both the array and the object inside the array which you want to update. For changing the reference of the array you an use map method, which returns a new array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.