|
| 1 | +import { |
| 2 | + action, |
| 3 | + createOptimisticStore, |
| 4 | + createRenderEffect, |
| 5 | + createRoot, |
| 6 | + createSignal, |
| 7 | + createStore, |
| 8 | + flush |
| 9 | +} from "../src/index.js"; |
| 10 | + |
| 11 | +const tick = () => new Promise<void>(r => setTimeout(r, 0)); |
| 12 | +async function drain(n = 3) { |
| 13 | + for (let i = 0; i < n; i++) { |
| 14 | + await tick(); |
| 15 | + flush(); |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +type Card = { id: number; title: string; failed?: boolean; saving?: boolean }; |
| 20 | + |
| 21 | +// #3796: an action's write to a row of the derived store an optimistic store |
| 22 | +// wraps holds that row's staging; the optimistic write that follows edits the |
| 23 | +// row's keys, not the container's slot — the slot is the same row in both |
| 24 | +// frames and is no guess. The edit shows while the action is pending (A17). |
| 25 | +describe("optimistic store over a row the action holds (#3796)", () => { |
| 26 | + for (const localWrite of [true, false]) |
| 27 | + it(`shows the guesses while pending${localWrite ? " after a local write" : ""}`, async () => { |
| 28 | + const shown: string[] = []; |
| 29 | + let save!: () => Promise<void>; |
| 30 | + let complete!: () => void; |
| 31 | + createRoot(() => { |
| 32 | + const [server, setServer] = createSignal<Card[]>([{ id: 1, title: "Old" }]); |
| 33 | + const [local, setLocal] = createStore<Card[]>(draft => { |
| 34 | + const s = server(); |
| 35 | + draft.length = 0; |
| 36 | + for (const r of s) draft.push({ ...r, failed: false }); |
| 37 | + }, []); |
| 38 | + const [cards, setOptimistic] = createOptimisticStore(local); |
| 39 | + createRenderEffect( |
| 40 | + () => `${cards[0]?.title} / saving: ${!!cards[0]?.saving}`, |
| 41 | + v => { |
| 42 | + shown.push(v); |
| 43 | + } |
| 44 | + ); |
| 45 | + save = action(function* () { |
| 46 | + if (localWrite) |
| 47 | + setLocal(draft => { |
| 48 | + draft[0].failed = false; |
| 49 | + }); |
| 50 | + setOptimistic(draft => { |
| 51 | + draft[0].title = "New"; |
| 52 | + draft[0].saving = true; |
| 53 | + }); |
| 54 | + yield new Promise<void>(r => (complete = r)); |
| 55 | + setServer([{ id: 1, title: "New" }]); |
| 56 | + }); |
| 57 | + }); |
| 58 | + flush(); |
| 59 | + expect(shown).toEqual(["Old / saving: false"]); |
| 60 | + const p = save(); |
| 61 | + await drain(); |
| 62 | + expect(shown).toEqual(["Old / saving: false", "New / saving: true"]); |
| 63 | + complete(); |
| 64 | + await p; |
| 65 | + await drain(); |
| 66 | + expect(shown.at(-1)).toBe("New / saving: false"); |
| 67 | + }); |
| 68 | +}); |
0 commit comments