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?