Undo delete
A todo list where Delete removes the todo at once and shows a toast with Undo. For five seconds the request waits. Undo puts the todo back and nothing is sent. When the time runs out, the delete is sent, and if the server fails, the todo comes back.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useFetch } from "@hyper-fetch/react";
import { useState } from "react";
import { getTodosRequest, setFailDeletes } from "./api";
import { undoTime, useUndoDelete } from "./use-undo-delete";
import type { PendingDelete } from "./use-undo-delete";
const Toast = ({ item, onUndo }: { item: PendingDelete; onUndo: () => void }) => (
<article className="toast">
{item.status === "waiting" && (
<>
<div className="toolbar">
<span>Deleted "{item.todo.todo}"</span>
<button type="button" className="outline" onClick={onUndo}>
Undo
</button>
</div>
{/* The bar empties in `undoTime`. When it is empty, the request is sent. */}
<div className="countdown" style={{ animationDuration: `${undoTime}ms` }} />
</>
)}
{item.status === "deleting" && <span aria-busy="true">Deleting "{item.todo.todo}"...</span>}
{item.status === "failed" && (
<span className="error">Could not delete "{item.todo.todo}". It is back in the list.</span>
)}
</article>
);
export const App = () => {
const [fail, setFail] = useState(false);
const { data, error, loading } = useFetch(getTodosRequest);
const { pending, deleteTodo, undo } = useUndoDelete();
return (
<main className="container narrow">
<hgroup>
<h1>Todos</h1>
<p>Delete a todo. You have five seconds to undo before the request is sent.</p>
</hgroup>
<label>
<input
type="checkbox"
role="switch"
checked={fail}
onChange={(event) => {
setFail(event.target.checked);
setFailDeletes(event.target.checked);
}}
/>
Make deletes fail
</label>
{loading && !data && <p aria-busy="true">Loading todos...</p>}
{error && <p className="error">Could not load todos: {error.message}</p>}
{data?.todos.length === 0 && <p className="muted">Nothing left. Reload the page to get the todos back.</p>}
<ul className="todos">
{data?.todos.map((todo) => (
<li key={todo.id}>
<span>{todo.todo}</span>
<button type="button" className="outline secondary" onClick={() => deleteTodo(todo)}>
Delete
</button>
</li>
))}
</ul>
<div className="toasts" aria-live="polite">
{pending.map((item) => (
<Toast key={item.todo.id} item={item} onUndo={() => undo(item.todo.id)} />
))}
</div>
</main>
);
};
npx tiged BetterTyped/hyper-fetch/examples/react/undo-delete hyper-fetch-react-undo-delete && cd hyper-fetch-react-undo-delete && npm install && npm run devsetOptimisticon the delete request removes the todo from the cached list as soon as it is sent.- A stopped queue holds the request:
submitDispatcher.stop(queryKey)beforesend(),start(queryKey)later. - Undo without a request:
clearQueue(queryKey)removes the waiting request, and core rolls back with the reason"removed". - Rollback on failure: turn on Make deletes fail and the todo returns after the error.
How it works
-
api.tsgivesdeleteTodoRequestan optimistic update..remove(params.todoId)takes the todo out of the cached list, and.rollback()puts it back at its old index usingprevious, the list from just before the change. -
useUndoDeletestops the queue of this one delete before sending it:const { queryKey } = deleteTodoRequest.setParams({ todoId: todo.id });client.submitDispatcher.stop(queryKey);const response = await request.send();send()applies the optimistic change and adds the request to the queue, but a stopped queue does not run it. The endpoint contains the todo id, so every todo has its own queue and deletes do not wait for each other. -
A timer calls
submitDispatcher.start(queryKey)after five seconds. The request runs, andsend()resolves with the server's answer. -
Undo clears the timer and calls
submitDispatcher.clearQueue(queryKey). The request is removed before it was sent, core runs the rollback with the reason"removed", andsend()resolves withsuccess: false. The queue is started again so a later delete of the same todo is not stuck. -
A failed delete runs the same rollback with the reason
"error". The hook shows a message for a few seconds. -
The request returns
revalidate: false, because dummyjson does not store deletes and a refetch would bring the todo back. With a real API, leave revalidation on.
- Destructive actions where a confirm dialog is too much friction: archive, delete, remove from a list.
- Keep the waiting time short and do not hold requests that other parts of the app depend on. A request that already reached the server cannot be undone by the client.
Related
The delete is sent right away into a stopped queue, so the optimistic removal shows at once while the request waits. Clearing the queue is the undo, and core rolls the list back for an undo, an abort or a failed response.
