47
rated 0 times
[
49]
[
2]
/ answers: 1 / hits: 20364
/ 6 Years ago, thu, july 5, 2018, 12:00:00
React newbie is messing things up, sorry, but really tried for hours ;( see attempts below.
Simple task: Trying to update an object in an array of objects.
This should be fairly easy though after research of a dozen answers, trying a bunch of possible solutions I still get errors. I can't figure out what I am missing here.
Here are my 4 attempts:
Attempt 1
updateText = (updatedText) => {
var arrTexts = {...this.state.arrTexts}
var myObjectToUpdate = arrTexts.filter(x => x.id === updatedText.id);
myObjectToUpdate = updatedText;
console.log (myObjectToUpdate);
console.log (arrTexts);
};
Attempt 2:
updateText = (updatedText) => {
var arrTexts = {...this.state.arrTexts}
var myObjectToUpdate = arrTexts.find(function (myObjectToUpdate) { return myObjectToUpdate.id === updatedText.id; });
myObjectToUpdate = updatedText
console.log (myObjectToUpdate);
console.log (arrTexts);
};
Attempt 3
updateText = (updatedText) => {
var arrTexts = {...this.state.arrTexts}
var myObjectToUpdate = arrTexts.findIndex(x => x.id === updatedText.id);
myObjectToUpdate = updatedText;
console.log (myObjectToUpdate);
console.log (arrTexts);
};
Attempt 4
updateText = (updatedText) => {
var arrTexts = {...this.state.arrTexts}
var myObjectToUpdate = _.findWhere(arrTexts, { id: updatedText.id });
myObjectToUpdate = updatedText;
console.log (myObjectToUpdate);
console.log (arrTexts);
};
The updateText comes from another component that includes an form and handles onSubmit this function:
handleUpdate = event => {
event.preventDefault();
const updatedText = {
...this.props.arrText,
id: this.idRef.current.value,
title: this.titleRef.current.value,
author: this.authorRef.current.value,
};
this.props.updateText(updatedText);
};
Thanks so much for helping out!
More From » reactjs