0

This is a function which on click of an dropdown element changes a isSelected property to true or false and on the basis of isselected property it displays Cannot assign to read only property 'isSelected' of object

     onCheckUsers = (x) => {
    console.log(x, "param of x");

    var { userFilter } = this.props.main;
    var { length } = this.state;

    var tempSelected = userFilter.find((a) => a.name === x.name);

    if (tempSelected.isSelected) {
      tempSelected.isSelected = false;
    } else tempSelected.isSelected = true;

    console.log(userFilter, "selectedUserList");
    StoreActions.setState({ userFilter });
    length = userFilter.filter((d) => d.isSelected).length;

    this.setState({ length });
    // Actions.storeSetState({ userFilter });
  };
Abhishek Roy
  • 65
  • 1
  • 8
  • The message is pretty clear: It's telling you that `isSelected` is a read-only property of the object it's on, so you can't assign to it. It's entirely possible to make properties read-only. Separately, assigning to a property on an object you received via props is poor practice. Props are owned and controlled by the parent component. If you want to change them, you need to ask the parent to change them (so rendering occurs). – T.J. Crowder Mar 22 '22 at 13:47
  • from here i am trying to update the property in redux store. if you can help me a bit with the code how to improve. that would be of much help – Abhishek Roy Mar 22 '22 at 13:49
  • [This search](/search?q=%5Bredux%5D+how+to+update+value) turns up [this helpful looking post](https://stackoverflow.com/questions/35628774/how-to-update-single-value-inside-specific-array-item-in-redux) and many others. But if you're wondering how to update a value in a Redux store, I suggest stepping back from your current task and working through a Redux tutorial or two. You can't just assign to the object. Happy coding! – T.J. Crowder Mar 22 '22 at 14:07

1 Answers1

0

So here i found the answer by myself that you cannot update the state of a redux store directly so for that you need to update the state in the current context and then assign the value to it. I am not really sure weather its the right explanantion or not but for me it worked. so here i am attching the code if anyone feels to optimise it please you are welcome

var { userFilter } = this.props.main;
var { length , tempSelected=[]} = this.state;

var tempSelected = _.cloneDeep(userFilter);
var newtemplist= tempSelected.find((a) => a.name === x.name)
if (newtemplist.isSelected) {
  newtemplist.isSelected = false;
} else newtemplist.isSelected = true;
this.setState({tempSelected:newtemplist})
console.log(userFilter, "selectedUserList");
StoreActions.setState({ userFilter:tempSelected });
Abhishek Roy
  • 65
  • 1
  • 8