Solarflare

Optimistic Updates

We've just shipped the optimistic updates API for Solarflare, that will make your UI feel extra fast. Here's how it works:

Let's say you're calling a REST endpoint, that updates a row in your Postgres database table todos. Your handler might start out looking like this:

index.tsx
const Todos = () => {
  const updateTodo = async (id: number, text: string) => {
    const res = /* call your normal API here */;
  };

  return (
    <div>
      {data.map((todo) => (
        <Todo key={todo.id} todo={todo} updateTodo={updateTodo} />
      ))}
    </div>
  );
};

When you call updateTodo, you're waiting for the server to respond before updating the UI.

Now, instead you can perform an optimistic update, and update the UI before the server has even responded. This is how you can do it:

index.tsx
const Todos = () => {
  const { data, optimistic } = useTable("todos");

  const updateTodo = async (id: number, text: string) => {
    // Optimistically update the UI
    const { rollback } = optimistic({
      action: "update",
      id,
      data: { text },
    });

    const res = /* call your normal API here */;

    // If the server responds with an error,
    // roll back the optimistic update
    if (res.error) {
      rollback();
    }
  };

  return (
    <div>
      {data.map((todo) => (
        <Todo key={todo.id} todo={todo} updateTodo={updateTodo} />
      ))}
    </div>
  );
};

That's it! Your UI will now feel extra fast, and your users will love it.

Back to Changelog
Backed by
Made in San Francisco + London