Unable to insert a new item at a specific index into an array

Viewed 39

I am trying to insert a new item at a specific index into an array.

I have this code:

const insertAt = (index: number, ...element: QC[]) => {
  const arrCopy = [...qt]
  return arrCopy.splice(index, 0, ...element)
}

const newQC: QC[] = [
  {
    id: cuid(),
    order: qt.length + 1,
  }
]

questionIndex !== undefined &&
  setQt(qt => {
    return insertAt(questionIndex, ...newQC)
  })

What this is doing is that it deletes everything from the array returned by setQt.

setQt is a useState function so it has to return a new state.

What could possibly be wrong with my code?

3 Answers

Splice returns the deleted items (in your case you have 0 deleted items as a second argument) so it returns an empty array. I think, you need something like that

const insertAt = (index: number, ...element: QC[]) => {
    const arrCopy = [...qt];
    arrCopy.splice(index, 0, ...element);
    return arrCopy;
}

You can directly use spread syntax for inserting:

return [...qt.slice(0, index), ...element, ...qt.slice(index)];
Related