I have an array of objects formatted like this:
{
"_id": "590cbcd9bf2b9b18ab3c3112",
"title": "",
"content": "Create Notes Webapp",
"checked": true,
"listID": "590cbc61bf2b9b18ab3c3110"
},
{
"_id": "590cfe5a86fe0908c560c2b0",
"title": "A Note 01",
"content": "My first note.",
"checked": false,
"listID": "590cbe15bf2b9b18ab3c3114"
}
Here is the code I have to update each item:
onTextChange = (key, note, value) => {
clearTimeout(timeoutID);
switch (key) {
default:
break;
case 'title':
note.title = value;
break;
case 'checked':
note.checked = value;
break;
case 'content':
note.content = value;
break;
}
var notes = this.state.notes;
var id;
for (var i in notes) {
if (notes[i]._id === note._id) {
notes[i] = note;
id = i;
break;
}
}
this.setState({ notes }, () => { timeoutID = setTimeout(() => this.updateNote(this.state.notes[id]), 3000); });
}
This is called like this:
onChange={(e, value) => this.onTextChange('title', note, value)}
Is there a better way than using that switch statement to update the specified item in the object? Also, is there a simpler method of scanning the array for the id than the for loop?
setState({notes}, ()=>{//your code})