Last active
July 15, 2017 12:28
-
-
Save RajaJaganathan/0fdaf43ded6215a1eb09c6185770cd29 to your computer and use it in GitHub Desktop.
immutability helper functions for javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Immutable specfic object in the array | |
onUpdateItem(index, e) { | |
const options = [...this.state.options]; | |
const newObject = { | |
...options[index], | |
[fieldName]: event.target.value | |
}; | |
options.splice(index, 1, newObject); | |
this.setState({ options }); | |
} | |
// Mutable array example | |
onUpdateItem2(index, e) { | |
const groups = [...this.state.groups]; | |
groups[index].name = e.target.value; | |
this.setState({ groups }); | |
} | |
} | |
onAddItem() { | |
const newRow = { | |
id: uniqueId('option-') | |
}; | |
const rows = [...this.state.rows, newRow]; | |
this.setState({rows}); | |
} | |
onDeleteItem(deleteIdx) { | |
const rows = this.state.rows.filter((item, idx) => idx !== deleteIdx); | |
this.setState({rows}); | |
} | |
onDeleteItem2(deleteIdx) { | |
let {rows} = this.state; | |
rows = [ | |
...rows.slice(0,deleteIdx), | |
...rows.slice(deleteIdx+1), | |
]; | |
this.setState({rows}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment