Manage items position field after delete

Hey, I'm working currently on todo list where user can change position of task using drag and drop. To do this i need number field on task to know on which position he is. And there is my question - if i have 5 items and someone deletes item 3 for example. should i change 4th and 5th items position to -1? I'm now using items length to set newly created task position (which isn't perfect i guess?). So, should I decrement positions that are higher than deleted one? Or there is some other solution? here is my Task schema
model Task {
id String @default(cuid())
position Int
text String
isCompleted Boolean @default(false)
user User @relation(fields: [userId], references: [id])
userId String

@@unique([id, position])
@@index([userId])
}
model Task {
id String @default(cuid())
position Int
text String
isCompleted Boolean @default(false)
user User @relation(fields: [userId], references: [id])
userId String

@@unique([id, position])
@@index([userId])
}
4 Replies
Neto
Neto2y ago
It's a nice approach Even more considering that when you add the next item you can just get the highest position easily
Paweł
Paweł2y ago
Nice, that's encouraging! thx. Then I have small followup question, if I get all tasks with higher position then decrementing them in for loop with saving to db will be acceptable?
Neto
Neto2y ago
Prisma does have a "native" decrement operation Just do it inside a transaction to avoid major issues
Paweł
Paweł2y ago
Oh, that's awesome 😄 Thanks a lot!
Want results from more Discord servers?
Add your server