Skip to content

Instantly share code, notes, and snippets.

@RajaJaganathan
Last active July 15, 2017 12:28
Show Gist options
  • Save RajaJaganathan/0fdaf43ded6215a1eb09c6185770cd29 to your computer and use it in GitHub Desktop.
Save RajaJaganathan/0fdaf43ded6215a1eb09c6185770cd29 to your computer and use it in GitHub Desktop.
immutability helper functions for javascript
// 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