Trying To Update Object In Array"> Trying To Update Object In Array">
Ad

React: "Error T.filter Is Not A Function" Or "Error: Uncaught TypeError: T.find Is Not A Function" --> Trying To Update Object In Array

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!

Ad

Answer

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);
};
Ad
source: stackoverflow.com
Ad