Add Zustand optimistic update pattern documentation
Document the Zustand optimistic update pattern with rollback for drag-and-drop functionality.
This commit is contained in:
parent
81053d0414
commit
963265eb8d
1 changed files with 27 additions and 0 deletions
27
patterns/zustand-optimistic.md
Normal file
27
patterns/zustand-optimistic.md
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
# Patroon: Zustand optimistische update + rollback
|
||||
|
||||
Gebruik dit patroon bij elke dnd-kit `onDragEnd` handler.
|
||||
|
||||
```ts
|
||||
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')
|
||||
}
|
||||
}
|
||||
```
|
||||
Loading…
Add table
Add a link
Reference in a new issue