Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

optimistic-actions.mdx

135 lines4.6 KB

import {Link} from '@tanstack/react-router' import { GHLink, HighLightComponent, ClearHighlightsButton, } from '/src/components/tutorial'

Optimistic Actions

Moving task between boards

In our highly sophisticated todo app, the positions of the todo items are stored in a column of the projects table. It's a json array:

[
    "board-1": ["task-1", "task-2", ...],
    "board-2": [...],
    "board-2": [...]
]

When new task is created, we need to update two different tables in our database:

  1. todo-items: we insert the new task's record into this table
  2. projects: the json array in the item_positions_in_the_project column must be updated to reflect the new orders of the tasks on the boards

The naive approach

At first, you might want to do something like this:

todoItemsCollection.insert(/*... */);
projectsCollection.update(/* ... */);

There's a problem with this approach: what happens if one of the requests fail? For example:

  • ✅ the new todo item gets inserted successfully,
  • ❌but the project can't be updated for some reason
    • this means that the changes made to the project will be rolled back

Oh no! 💀 Now we don't know where the task is on the board.

The solution: createOptimisticAction()

At this point, what we want is an action that does the following:

  • optimistically updates both collections in the cache
  • sends one request to the api, that attempts to update both tables (in a db transaction on the backend)
  • rolls back all optimistic changes if any of the tables can't be updated

This can be all done with optimistic actions:

const createTodoItem = createOptimisticAction({
  id: "create-todo-item",
  autoCommit: true,
  onMutate: (newItemData: CreateTodoItemInput) => {
    // This insert statement here will not actually trigger
    // the  `onInsert` function we defined when we created
    // the `todoItemsCollection`.
    // It'll only update the local cache optimistically.
    todoItemsCollection.insert({
      createdAt: new Date(),
      ...newItemData,
      priority: 0,
    });

    // Just like the `insert()` method above, this will also
    // not run the `onUpdate` function on the `projectsCollection`.
    projectsCollection.update(newItemData.projectId, (project) => {
      project.itemPositionsInTheProject[newItemData.boardId].unshift(
        newItemData.id,
      );
    });
  },
  mutationFn: async (newItemData: CreateTodoItemInput) => {
    // send a fetch request to the server
    await insertTodoItem({
      data: newItemData,
    });
    // We need to manually sync the data back from the server
    await todoItemsCollection.utils.refetch();
    await projectsCollection.utils.refetch();
  },
});

The insertTodoItem is basically a fetch request to a server endpoint:

export async function insertTodoItem({
  data,
}: {
  data: TodoItemCreateDataType;
}) {
  const res = await fetch("/api/todo-items", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });

  if (!res.ok) {
    throw new Error("Failed to insert todo item");
  }

  const response: TodoItemRecord = await res.json();

  return response;
}

You can check the backend's endpoint in the repo if you're interested.

Now you can use createTodoItem() when you want to insert a new todo items and be sure that the two tables will always be in sync with each other:

createTodoItem({ /* the data of the todo item */ });

Read more about optimistic actions in the docs.

More complex mutations

If you need even more control (e.g.: opting out from the optimistic updates, etc.), check out the Mutations page in the docs.