Search code examples
javascriptarraysreactjsstatesetstate

How to fix Do not mutate state directly. Use setState() with array?


I have an array tranches: [{ start: moment().format("HH:mm"), end: moment().format("HH:mm") }] and when I set the value of the tranches[0].start without setState I get :

Do not mutate state directly. Use setState()

My code is :

handleAjouter = (start, end, date) => {
    this.state.tranches[0].start = start;
    this.state.tranches[0].end = end;
    this.setState({
      tranches: this.state.tranches
    });
  }

How can I fix it ?


Solution

  • Clone the tranches[0] object instead of mutating it, which you can achieve concisely with object spread:

    handleAjouter = (start, end, date) => {
      const [firstTranch] = this.state.tranches;
      this.setState({
        tranches: [
          { ...firstTranch, start, end },
          ...tranches.slice(1)  // needed if the array can contain more than one item
        ]
      });
    }
    

    If you need to insert the changed tranch at a specific index, then clone the array and insert the tranch:

    const tranches = this.state.tranches.slice();
    tranches[index] = { ...tranches[index], someOtherProp: 'foo' };