React: "Error t.filter is not a function" or "Error: Uncaught TypeError: t.find is not a function" --> Trying to update object in array
13,867
filter
, find
and findIndex
are all functions applicable on array. You data seems to be an array, but are cloning it to an object. You would clone it like var arrTexts = [...this.state.arrTexts]
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);
};
Also you would update it like
handleUpdate = event => {
event.preventDefault();
const updatedText = {
id: this.idRef.current.value,
title: this.titleRef.current.value,
author: this.authorRef.current.value,
};
this.props.updateText(updatedText);
};
Related videos on Youtube
Comments
-
YvonC almost 2 years
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!
-
YvonC almost 6 yearsthanks so much! That was it. I had this old line in the "handleUpdate ... this.props.arrText that changed everything to an object. Hours of wasting time... thanks again. ;)