lundi 14 janvier 2019

Check if state is dirty or clean in React

I have a state that holds a list of items and checkboxes which are either assigned false or true by default (depending on the API I'm working with).

For simplicity let's say that I have my state like this.

state = { 
  list: [
    {
    id: 0,
    name: 'item1'
    assigned: true
    }
  ],
   dirtyList: []
}

When a checkbox is clicked, you press a button and the popup tells you if the item was registered or removed (checkbox is true/false). But let's say that you start the page with a checkbox already checked and then you click it two times (making it checked true again), the popup should not say that the item has been registered because the original state hasn't changed. (It went from true, false, then back to true)

Here is my checkbox handleChange function

checkboxChanged = (event, id) => {    
let isChecked = event.target.checked
const index = this.state.list.findIndex(list => list.id === id)
const newState = [...this.state.list]
let newList = { ...newState[index] }
console.log(newList) 
// By console logging this, it eventually tells me the previous state of the item that was clicked

newState[index].assigned = isChecked
this.setState({
  list: newState,
})
}

I'm having a hard time figuring out how/where I can update the 'dirtyList' state because only then I can compare the original state with the dirty one.




Aucun commentaire:

Enregistrer un commentaire