Skip to main content

Drag to reorder

A todo list you reorder by dragging, or with the arrow buttons. The new order shows at once while the save takes a second. Turn on Make saves fail and the todo slides back to where it was when the error arrives.

intermediateuseSubmitoptimisticmocking
import { useFetch, useSubmit } from "@hyper-fetch/react";
import { useState } from "react";
import type { DragEvent } from "react";

import { getTodosRequest, moveTodoRequest, setFailMoves } from "./api";

export const App = () => {
const [fail, setFail] = useState(false);
const [dragged, setDragged] = useState<number | null>(null);
const [over, setOver] = useState<number | null>(null);
const [log, setLog] = useState<string[]>([]);
const addLog = (line: string) =>
setLog((lines) => [`${new Date().toLocaleTimeString()} ${line}`, ...lines].slice(0, 5));

const { data, error, loading } = useFetch(getTodosRequest);
const { submit, submitting, onSubmitSuccess, onSubmitError } = useSubmit(moveTodoRequest);

onSubmitSuccess(({ response }) => addLog(`Saved the new position of #${response.data.id}`));
// By the time this runs, core has already moved the todo back.
onSubmitError(({ response }) => addLog(`Save failed (${response.status}), moved back`));

const move = (todoId: number, position: number) => {
const current = data?.todos.findIndex((todo) => todo.id === todoId);
if (current === undefined || current === position || position < 0) return;
// The list changes inside `submit`, before the request is sent.
submit({ params: { todoId }, payload: { position } });
};

// Moving down puts the todo after the target, moving up puts it before. The line shows that side.
const draggedIndex = data?.todos.findIndex((todo) => todo.id === dragged) ?? -1;
const getDropClass = (todoId: number, index: number) => {
if (todoId === dragged) return "dragging";
if (index !== over || draggedIndex < 0) return undefined;
return index > draggedIndex ? "drop-after" : "drop-before";
};

const handleDrop = (event: DragEvent, index: number) => {
event.preventDefault();
if (dragged !== null) move(dragged, index);
setDragged(null);
setOver(null);
};

return (
<main className="container narrow">
<hgroup>
<h1>Reorder todos</h1>
<p>Drag a todo to a new place, or use the arrows. The list changes at once and the server answers later.</p>
</hgroup>

<label>
<input
type="checkbox"
role="switch"
checked={fail}
onChange={(event) => {
setFail(event.target.checked);
setFailMoves(event.target.checked);
}}
/>
Make saves fail
</label>

{loading && !data && <p aria-busy="true">Loading todos...</p>}
{error && <p className="error">Could not load todos: {error.message}</p>}

<ol className="todos">
{data?.todos.map((todo, index) => (
<li
key={todo.id}
draggable
className={getDropClass(todo.id, index)}
onDragStart={() => setDragged(todo.id)}
onDragEnd={() => {
setDragged(null);
setOver(null);
}}
// Allowing the drop is opt-in: without preventDefault the browser refuses it.
onDragOver={(event) => {
event.preventDefault();
setOver(index);
}}
onDrop={(event) => handleDrop(event, index)}
>
<span className="handle" aria-hidden="true">
⠿
</span>
<span className="text">{todo.todo}</span>
<button
type="button"
className="outline secondary"
aria-label="Move up"
onClick={() => move(todo.id, index - 1)}
>
↑
</button>
<button
type="button"
className="outline secondary"
aria-label="Move down"
onClick={() => move(todo.id, index + 1)}
disabled={index === data.todos.length - 1}
>
↓
</button>
</li>
))}
</ol>

<article>
<header className="toolbar">
<strong>Log</strong>
<small aria-busy={submitting}>{submitting ? "Saving..." : "Idle"}</small>
</header>
{log.length === 0 ? (
<p className="muted">Move a todo.</p>
) : (
<ol className="log">
{log.map((line, index) => (
<li key={`${index}-${line}`}>{line}</li>
))}
</ol>
)}
</article>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/drag-reorder hyper-fetch-react-drag-reorder && cd hyper-fetch-react-drag-reorder && npm install && npm run dev
What it shows
  1. Native drag and drop: draggable, onDragStart, onDragOver and onDrop, no library.
  2. setOptimistic with .set() moves the todo in the cached list before the request is sent.
  3. A precise rollback moves only that todo back, so other moves made in the meantime stay.
  4. Mocked failures with setMock and setMockingEnabled, switched from the UI.

How it works​

  1. moveTodoRequest sends the new position of one todo: PATCH /todos/:todoId with { position }. dummyjson accepts it but does not store the order, so the request returns revalidate: false to stop a refetch from undoing the move.

  2. Its optimistic update uses the generic .set() helper with a small moveTodo() function:

    optimistic(getTodosRequest)
    .set((data) => ({ ...data, todos: moveTodo(data.todos, todoId, payload.position) }))
    .rollback(({ data, previous }) => {
    const oldIndex = previous.todos.findIndex((todo) => todo.id === todoId);
    return { ...data, todos: moveTodo(data.todos, todoId, oldIndex) };
    });

    The rollback reads the old index from previous and moves the todo back inside the current data. Returning previous as it is would also undo any other move that finished in the meantime.

  3. App.tsx calls submit({ params: { todoId }, payload: { position } }) from the drop handler and from the arrow buttons. The component has no cache code; useFetch re-renders from the updated cache.

  4. onDragOver must call preventDefault(), otherwise the browser does not allow the drop. The drop line shows the side where the todo will land: below the target when you drag down, above it when you drag up.

  5. onSubmitError runs after core has moved the todo back, so it only writes to the log.

When to use it
  • Sortable lists, kanban columns, playlists and priorities where the user expects the new order right away.
  • Send the position of the moved item, not the whole list, so two quick moves do not overwrite each other.
  • Native drag and drop does not work with touch on every device. The arrow buttons also make the list usable with a keyboard.

Summary

Native drag and drop picks the new position, setOptimistic moves the todo in the cache before the request goes out, and a rollback built from previous moves it back only if the save fails.