Search code examples
reactjscomponents

Why 'map()' method in my react component is changing/updating state?


I am using map() method in one of my function in React component to generate a new array which I will use to update the state using setState() method. but when I generate the new array (modified by map method) then state of my component is also getting updated. Eventhough I havent used setState method yet. (ofcourse the change of state is not visible, it didnt updated in browser yet, cuz setState() method hasnt been called yet, but backstage the state is updated.) I dont know WHY!!!

class Color1 extends Component {
  state = {
    colors: [
      { key: 1, color: 'green' },
      { key: 2, color: 'red' },
      { key: 3, color: 'red' },
      { key: 4, color: 'green' },
    ],
  };

  changeColor = color => {
    console.log(this.state.colors);
    const pehli = this.state.colors.map(e => {
      if (e.key === color.key) {
        e.color = e.color === 'green' ? 'red' : 'green';
        return e;
      } else {
        return e;
      }
    });
   
    console.log(
      this.state.colors
    );** /* For checking the state and it is updated */**
  };

// So 'pehli' was supposed to be a new seperate array, it was supposed to mutate the colors array in state. But it does


Solution

  • you are mutating the original object here e.color = e.color === 'green' ? 'red' : 'green'; ... instead make a copy as

      changeColor = color => {
        console.log(this.state.colors);
        const pehli = this.state.colors.map(e => {
          const el = {...e};  // a copy here
          if (el.key === color.key) {
            el.color = el.color === 'green' ? 'red' : 'green';
          }
          return el
        });
       
        console.log(
          this.state.colors
        );
      }