Home > Software engineering >  Update complex object using setState
Update complex object using setState

Time:08-16

I have array of data and just want to update whenever user click button:

const [visualQuerryData, setVisualQuerryData] = useState([{
  default: {
    default: [{
      class: '',
      property: ''
    }],
    and: [],
    or: [],
  },
}]);

In this I just want to update class key that's inside default object

What I did:

setVisualQuerryData((p) => [
  ...p,
  (visualQuerryData[0].default.default[i].class = e),
]);

What output I'm getting:

[{
    default: {
      and: []
      default: [{
        class: 'shanum',
        property: ''
      }],
      or: [],
    }
  },
  "shanum"
]

What is actual output:

[{
  default: {
    default: [{
      class: 'shanum',
      property: ''
    }],
    and: [],
    or: [],
  },
}]

I don't know why at the end same data added what I want to add in class key?

CodePudding user response:

You could use Immer to make state modifications easier by using the produce function. Immer takes the currentQueryState and returns a copy i.e. draft state so you are not mutating the original state. This makes state updates more readable.

import produce from 'immer';

// Where `e` and `i` are defined in the current stacktrace...

setVisualQuerryData((currentQueryData) =>
  produce(currentQueryData, (draft) => {
    draft[0].default.default[i].class = e;
  })
);

Don't forget to install the depoendency:

npm install immer

CodePudding user response:


const onChange = (e) => {
// object copy
 const nextValue =  {...visualQuerryData};

// change value
 nextValue[0].default.default[i].class = e;
// update value 
setVisualQuerryData(nextValue)
};

  • Related