Help with Spread Operator in React

Asked

Viewed 87 times

0

I have an array of objects saved in my state.

 const [rows, setRows] = useState();

Every time I click on a button it triggers this function

function processRow(value) {
   setRows(row=>[ ...row, row[value.rowIndex] = value.data]);
  }

in the parameter of my function it returns me the object with the data, with the object index in the state and the value. What I wish would be that whenever I gave the setRows it fetches the data and updates only the object at the position I passed. However instead it makes a copy of the state and adds the value below.

0: {MotivoTroca: "Motivo", ContadorInicial: "Contador", DataHora: "Data hora"}
1: {MotivoTroca: "Motivo", ContadorInicial: "Contador", DataHora: "Data hora"}
2: {MotivoTroca: "Motivo", ContadorInicial: "Contador", DataHora: "Data hora"}
3: {MotivoTroca: "Motivo", ContadorInicial: "Contador", DataHora: "Data hora"}

serious expected return

0: {MotivoTroca: "Motivo", ContadorInicial: "Contador", DataHora: "Data hora"}

1 answer

-2


The spread function is just this, it will keep everything that already exists and add the new record, if Voce wants it not to keep and just add the new, remove the spread:

function processRow(value) {
   setRows([row[value.rowIndex] = value.data]);
  }
  • 1

    That what you’re doing is also wrong, that way the setRows will receive an array with a single position. Also mutate the state using the current value as the basis, without the use of callback, can cause a running condition.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.