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

Đang mở
#4,642 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
25/100
Loại issue
Lỗi
Độ rõ ràng
Khá rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
javascript, typescript
Lĩnh vực
frontend

Hướng nghiên cứu

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.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

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
Ngôn ngữ chính
TypeScript
Star
36.2k
Fork
1.1k
Merge trung bình
10 giờ 39 phút
Pull request đã merge (30 ngày)
500

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của solidjs/solid

Tất cả issue của solidjs/solid

Issue tương tự

Thêm issue về TypeScript

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.