Document the Zustand optimistic update pattern with rollback for drag-and-drop functionality.
765 B
765 B
Patroon: Zustand optimistische update + rollback
Gebruik dit patroon bij elke dnd-kit onDragEnd handler.
const { pbiOrder, reorderPbis, rollbackPbis } = usePlannerStore()
async function handleDragEnd(event: DragEndEvent) {
const { active, over } = event
if (!over || active.id === over.id) return
const prevOrder = [...pbiOrder[productId]]
const newOrder = arrayMove(prevOrder, oldIndex, newIndex)
// 1. Optimistisch updaten (direct zichtbaar voor gebruiker)
reorderPbis(productId, newOrder)
// 2. Persisteren via Server Action
const result = await reorderPbisAction(productId, newOrder)
// 3. Rollback bij fout
if (!result.success) {
rollbackPbis(productId, prevOrder)
toast.error('Volgorde opslaan mislukt')
}
}