Skip to content
Advertisement

React state is updating but the component is not

There is a component that maps through an array stored in the state. A button, when it is clicked it updates the state, this action is working.

The problem is that the component is not updating too.

Here is the code:

const MyComponent = () => {
   ...
   const [fields, setFields] = useState([{value: 'test', editable: false},
                                         {value: 'test2', editable: false}]);

  ...

  const toggleClass = (id) => {
     const aux = fields;
     aux[id].editable = true;
     setFields(aux);
  }
  ...

  return (
     <div>
      ...
      {fields.map((field, id) => {
          return (
            <div>
              <input className={field.editable ? 'class1' : 'class2'} />
              <button onClick={() => toggleClass(id)}>click</button>
            </div>
          );
      })}
     </div>
  );

I put logs and the state (fields) is updated after click to editable = true. But the css class is not changing.

Is there any solution to this issue?

Advertisement

Answer

You need to make a copy of your existing state array, otherwise you’re mutating state which is a bad practice.

const toggleClass = id => {
  const aux = [...fields]; //here we spread in order to take a copy
  aux[id].editable = true; //mutate the copy
  setFields(aux); //set the copy as the new state
};
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement