πŸ‘‹ Introduction

Everything your project needs about Cache.

What is Optimistic UI?

Most HTTP requests or attempts to do something, if done correctly, are usually successful and behave as expected. That's why the idea behind Optimistic UI is to assume that, before sending the HTTP request, for example, it will be successful and confirmed, so we can tell the user that everything went well before even doing it and, if it fails, notify them that it went wrong.

Getting started

We will start with the easiest part of all, setting and then obtaining that value optimistically using useOptimistic.


Example: Set a random value in the cache with the key "key" and update the UI immediately. If something goes wrong, rollback to the previous value.

Like correctly
Like without internet
import { useOptimistic } from "toolkitify/optimistic-ui";

let value = 0;

await useOptimistic.promise(
    async () => {
        await new Promise((r) => setTimeout(r, 50));
        value += 2;
        return value;
    },
    {
        optimisticUpdate: () => {
            value += 1;
        },
        rollback: (error) => {
            value = 0;
        },
        onSuccess: (result) => {
            value = result;
        },
        finally: () => {
            console.log(value);
        }
    }
);