Loading...
Please waitLoading...
Please waitpnpm dlx uselab@latest add use-optimistic-queue
import * as React from "react"
import { useOptimisticQueue } from "@/hooks/use-optimistic-queue"
export function Component() {
const [items, setItems] = React.useState<string[]>([])
const { enqueue, confirm, rollback, pending, size } =
useOptimisticQueue<string>()
const handleAddItem = async (item: string) => {
const actionId = enqueue(item, () => {
setItems((prev) => prev.filter((i) => i !== item))
})
setItems((prev) => [...prev, item])
try {
await saveToServer(item)
confirm(actionId)
} catch (error) {
rollback(actionId)
}
}
return (
<div>
<p>Pending actions: {size}</p>
{items.map((item) => (
<div key={item}>{item}</div>
))}
</div>
)
}enqueue(action, rollback?):
confirm(id):
rollback(id):
queue:
pending:
size:
clear():
| Name | Type | Description |
|---|---|---|
enqueue | (action: T, rollback?: () => void) => string | Adds an action to the queue and returns a unique ID. Optionally accepts a rollback function. |
confirm | (id: string) => void | Confirms a queued action by removing it from the queue. |
rollback | (id: string) => void | Rolls back a queued action by calling its rollback function and removing it from the queue. |
clear | () => void | Clears all pending actions from the queue without calling rollback functions. |
queue | T[] | An array of all actions currently in the queue. |
pending | Array<{ id: string, action: T, rollback?: () => void }> | An array of all pending actions with their IDs and rollback functions. |
size | number | The number of pending actions in the queue. |
No todos yet
Click "Add Todo" to enqueue an optimistic update. After 2 seconds, it will either be confirmed (kept) or rolled back (removed) randomly.