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

クローズ
#4,642 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
25/100
issue の種類
バグ
明瞭さ
おおむね明確
活発さ
活発
技術スタック
javascript, typescript
領域
frontend

調査の方向性

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.

索引モデルが issue の本文から書いたものです。

説明

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
主要言語
TypeScript
スター
36.2k
フォーク
1.1k
平均マージ
10時間 10分
マージ済み PR(30日)
505

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

solidjs/solid のほかの issue

solidjs/solid の issue をすべて見る

似ている issue

TypeScript の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。