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
  • 44,815
  • 8
  • 87
  • 134
user1189352
  • 3,774
  • 9
  • 47
  • 81

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
  • 44,815
  • 8
  • 87
  • 134