[2.0 / next] createOptimisticStore: add, delete, add with saves pending hands <For> an undefined row

Aperta
#4,642 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
25/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
javascript, typescript
Ambito
frontend

Direzione di ricerca

Start by running the two vitest specs in packages/web/test/ against commit 42350195f to confirm the Cannot read properties of undefined throw. The bug sits in how createOptimisticStore records pending guesses and replays them by position when action saves and refresh(todos) land, so read that code path and how <For> consumes the store. Done means both fixture-driven add/delete/add cases render [milk][jam][tea] and [milk][eggs][tea], and the related list-first and declined-delete specs also pass.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Describe the bug

The todo list from the 2.0 cheatsheet: createOptimisticStore(() => api.list(), []), with add and remove actions that each write a guess, yield the save, then call refresh(todos). With both saves still out, add a todo, delete one (another row or the one just added), then add a second todo. The second add's guess hands <For> an undefined row, so t.title in the row callback throws Cannot read properties of undefined (reading 'title') and the new row never renders.

No server answer is needed after the list's first load: three clicks against any latency at all reproduce it. Push then filter, or filter then push, are fine; it takes push, filter, push with the earlier actions still pending. In the fuzz harness, where the throw did not stop the run, the second row stayed missing after every save and list refetch landed.

Found by fuzzing random sequences of these actions against a fake server and comparing the settled screen with the server's list.

Your Example Website or App

The vitest spec below (in packages/web/test/), on next @ 42350195f.

Steps to Reproduce the Bug or Issue
import { render } from "@solidjs/web";
import { action, createOptimisticStore, flush, For, Loading, refresh } from "solid-js";
import { expect, it } from "vitest";

const tick = async () => { for (let i = 0; i < 2; i++) { await new Promise(r => setTimeout(r, 0)); flush(); } };
type Todo = { id: number; title: string };

// The cheatsheet's todo list: add, delete, add, with every save still out.
for (const removeWhich of ["other", "just-added"] as const)
it(`add, delete (${removeWhich}), add: the second add's guess renders`, async () => {
  const out: { key: string; resolve: (v: any) => void }[] = [];
  const call = (key: string) => new Promise<any>(resolve => out.push({ key, resolve }));
  const el = document.createElement("div");
  let add!: (t: Todo) => Promise<unknown>, remove!: (id: number) => Promise<unknown>;
  const dispose = render(() => {
    const [todos, setTodos] = createOptimisticStore<Todo[]>(() => call("list"), []);
    add = action(function* (todo: Todo) { setTodos(s => { s.push(todo); }); yield call("add:" + todo.id); refresh(todos); });
    remove = action(function* (id: number) { setTodos(s => s.filter(x => x.id !== id)); yield call("remove:" + id); refresh(todos); });
    return <Loading fallback={<p>loading</p>}><For each={todos}>{t => <li>[{t.title}]</li>}</For></Loading>;
  }, el);
  await tick();
  out.shift()!.resolve([{ id: 1, title: "milk" }, { id: 2, title: "eggs" }]); await tick();
  add({ id: 3, title: "jam" }); flush(); await tick();
  remove(removeWhich === "other" ? 2 : 3); flush(); await tick();
  let error: string | null = null;
  try { add({ id: 4, title: "tea" }); flush(); await tick(); } catch (e) { error = (e as Error).message; }
  const frame = el.textContent;
  dispose();
  expect({ error, frame }).toEqual({ error: null, frame: removeWhich === "other" ? "[milk][jam][tea]" : "[milk][eggs][tea]" });
});

npx vitest run in packages/web. Both tests fail with error: "Cannot read properties of undefined (reading 'title')", and the frame stays at [milk][jam] (or [milk][eggs]).

Expected behavior

Each guess applies to the list as it currently stands: the second add shows tea at the end of the list, and the row callback never receives undefined.

Related shapes, likely the same cause

The same list corrupts in two other everyday sequences. Both settle to a wrong list that only a later, unrelated refresh repairs. In both, the guess looks recorded against one version of the list and applied by position to another.

  • Add a todo before the list's first load lands. The list settles to [milk][eggs][eggs] or [milk][milk][eggs], where the server has [milk][eggs][jam].
  • Delete a todo, the server declines, then add a todo. The list settles to [milk][eggs][milk], where the server has [milk][eggs][jam].
Spec for the add-during-first-load case
import { render } from "@solidjs/web";
import { action, createOptimisticStore, flush, For, Loading, refresh } from "solid-js";
import { expect, it } from "vitest";

const tick = async () => { for (let i = 0; i < 2; i++) { await new Promise(r => setTimeout(r, 0)); flush(); } };
type Todo = { id: number; title: string };

// The cheatsheet's todo list; the user adds a todo before the list has loaded.
async function run(order: "list-first" | "save-first") {
  let server: Todo[] = [{ id: 1, title: "milk" }, { id: 2, title: "eggs" }];
  const out: { key: string; go: () => void }[] = [];
  const call = (key: string, apply?: () => void) =>
    new Promise<any>(resolve => out.push({ key, go: () => { apply?.(); resolve(key === "list" ? server.map(t => ({ ...t })) : true); } }));
  const land = (key: string) => out.splice(out.findIndex(f => f.key === key), 1)[0].go();
  const el = document.createElement("div");
  const frames: string[] = [];
  let add!: (t: Todo) => Promise<unknown>;
  const dispose = render(() => {
    const [todos, setTodos] = createOptimisticStore<Todo[]>(() => call("list"), []);
    add = action(function* (todo: Todo) {
      setTodos(s => { s.push(todo); });
      yield call("add:" + todo.id, () => { server = [...server, todo]; });
      refresh(todos);
    });
    return <Loading fallback={<p>loading</p>}><For each={todos}>{t => <li>[{t.title}]</li>}</For></Loading>;
  }, el);
  await tick();
  add({ id: 3, title: "jam" }); flush(); await tick();
  if (order === "list-first") { land("list"); await tick(); frames.push(el.textContent!); land("add:3"); await tick(); }
  else { land("add:3"); await tick(); land("list"); await tick(); frames.push(el.textContent!); }
  while (out.length) { land(out[0].key); await tick(); }   // the add's refresh
  frames.push(el.textContent!);
  dispose();
  return frames;
}

it("the list lands while the add is saving", async () => {
  expect(await run("list-first")).toEqual(["[milk][eggs][jam]", "[milk][eggs][jam]"]);
});

it("the add is saved before the list lands", async () => {
  expect(await run("save-first")).toEqual(["[milk][eggs][jam]", "[milk][eggs][jam]"]);
});
Spec for the declined-delete case
import { render } from "@solidjs/web";
import { action, createOptimisticStore, flush, For, Loading, refresh } from "solid-js";
import { expect, it } from "vitest";

const tick = async () => { for (let i = 0; i < 2; i++) { await new Promise(r => setTimeout(r, 0)); flush(); } };
type Todo = { id: number; title: string };

// The cheatsheet's todo list: delete a todo, the server declines, then add another.
for (const renameFirst of [false, true])
it(`a declined delete, then an add, settles to the server's list (rename first=${renameFirst})`, async () => {
  let server: Todo[] = [{ id: 1, title: "milk" }, { id: 2, title: "eggs" }];
  const out: { key: string; go: (ok: boolean) => void }[] = [];
  const call = (key: string, apply?: () => void) => new Promise<any>((resolve, reject) =>
    out.push({ key, go: ok => { if (!ok) return reject(new Error(key)); apply?.(); resolve(key === "list" ? server.map(t => ({ ...t })) : true); } }));
  const land = (key: string, ok = true) => out.splice(out.findIndex(f => f.key === key), 1)[0].go(ok);
  const el = document.createElement("div");
  let rename!: (id: number, t: string) => Promise<unknown>, remove!: (id: number) => Promise<unknown>, add!: (t: Todo) => Promise<unknown>;
  const dispose = render(() => {
    const [todos, setTodos] = createOptimisticStore<Todo[]>(() => call("list"), []);
    rename = action(function* (id: number, title: string) {
      setTodos(s => { const t = s.find(x => x.id === id); if (t) t.title = title; });
      try { yield call("rename:" + id, () => { server = server.map(t => t.id === id ? { ...t, title } : t); }); } catch {}
      refresh(todos);
    });
    remove = action(function* (id: number) {
      setTodos(s => s.filter(x => x.id !== id));
      try { yield call("remove:" + id, () => { server = server.filter(t => t.id !== id); }); } catch {}
      refresh(todos);
    });
    add = action(function* (todo: Todo) {
      setTodos(s => { s.push(todo); });
      try { yield call("add:" + todo.id, () => { server = [...server, todo]; }); } catch {}
      refresh(todos);
    });
    return <Loading fallback={<p>loading</p>}><For each={todos}>{t => <li>[{t.title}]</li>}</For></Loading>;
  }, el);
  const step = async (f: () => void) => { f(); flush(); await tick(); };
  await step(() => land("list"));
  if (renameFirst) await step(() => { rename(1, "oat milk"); });
  await step(() => { remove(1); });
  await step(() => land("remove:1", false));     // the server declines the delete
  await step(() => { add({ id: 3, title: "jam" }); });
  while (out.length) await step(() => land(out[0].key));
  const settled = el.textContent;
  dispose();
  expect(settled).toBe(renameFirst ? "[oat milk][eggs][jam]" : "[milk][eggs][jam]");
});
Platform
  • OS: macOS
  • Browser: n/a (jsdom)
  • Version: solid-js 2.0.0-rc.20, next @ 42350195f
Lingua principale
TypeScript
Stelle
36.2k
Fork
1.1k
Merge medio
10h 39m
PR unite (30g)
500

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di solidjs/solid

Tutte le issue di solidjs/solid

Issue simili

Altre issue su TypeScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.