Home > Software engineering >  React best way to track changes to an array of objects
React best way to track changes to an array of objects

Time:11-23

Say I have an array of objects like this and it is stored in state:

interface CheckItem {
  label: string;
  checked: boolean;
  disabled: boolean;
}

const [checkboxes, setCheckboxes] = useState<CheckItem[] | undefined>(undefined);


const checkboxArr: CheckItem[] = [
{label: 'item1', checked: true, disabled: false}, 
{label: 'item2', checked: false, disabled: false}
];

useEffect(() => {
  setCheckboxes(checkboxArr);
}, [])

//should remain disabled until changes are made
//should revert to disabled if changes are undone
<Button disabled={disabled}>Apply Changes</Button>

I also have a button that should remain disabled until one of the original elements has been changed.

What is the best way to track changes that are made to any property of each element in the array? The array can be any length, so I would like to optimize for space/time.

CodePudding user response:

By what I can understand by your question is you want to know if someone is clicked on the checkbox or not right?

You can simply track changes by having the constant variable that you already created called checkBoxArr and compare it to a new array say tempCheckBoxArr.

So say we create an array const [tempCheckBoxArr, setTempCheckBoxArr] = useState<string[]>([])

This is an empty array and we can store the labels of the items in this array.

Now suppose you have an onclick function on the checkboxes.

So,

checkboxArr.map((checkbox) => {
  return(
      <div>
        <input type="checkbox" checked={checkbox.checked} onClick={() => handleCheckBox(checkbox.label)}/>
      </div>
  )
})

And the function handleCheckBox is :

const handleCheckBox = (label: string) => {
  if(!tempCheckBoxArr.includes(label)){
    tempCheckBoxArr.push(label)
    setTempCheckBoxArr(tempCheckBoxArr)
  }else{
    let tempArr = tempCheckBoxArr.filter((labelInclude) => labelInclude !== label)
    
    setTempCheckBoxArr(tempArr)
    
  }
}

By the length of the tempCheckBoxArr.length that we created you can then track if your button should be disabled or not and also if there are changes.

Thank you, please feel free to comment if you have questions.

  • Related