1

I'm sure this is a simple question but I can't figure this out.

const [rowLabels, setRowLabels] = React.useState(['','','','','',]);

i figured this would work. but it doesn't like the syntax.

setRowLabels(oldValues => ([
  ...oldValues,
  oldValues[position]: event.target.value
])

I know I can do this below, but I rather not pass down rowLabels as props to avoid the re-render. Is there a way I can do it with just the oldValues?

const rowLabelsCopy = [...rowLabels];
rowLabelsCopy[position] = event.target.value;
setRowLabels(rowLabelsCopy);
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
user1189352
  • 3,628
  • 12
  • 50
  • 90

1 Answers1

1

The setState() function accepts a callback as you demonstrated in your first failed attempt. That callback can contain the lines in your second attempt, and allow you to use oldValues instead of rowLabels:

setRowLabels(oldValues => {
  const newValues = [...oldValues];
  newValues[position] = event.target.value;
  return newValues;
});

Or if you don't want to use an explicit return, here's a slightly less readable alternative:

setRowLabels(oldValues => Object.assign(
  [...oldValues],
  { [position]: event.target.value }
));
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153