Self-referential Svelte state

I
• @isker
2mo ago
reproduce and explain the cause of https://github.com/isker/neogrok/issues/51. propose a fix.

Reproduced issue #51 locally.

Cause

previousSearchResults is a derived value that reads itself when the search fails:

return previousSearchResults;

That is recursive evaluation, not access to the previously computed value.

  • Development Svelte detects it as derived_references_self.
  • Production/SSR lacks that guard and recurses until RangeError: Maximum call stack size exceeded.
  • The exception kills the reactive rendering path. Further searches update the input and URL, but the displayed error/results remain stale until reload.
  • Opening an invalid query directly also returns HTTP 500.

The same latent bug exists in repositories/+page.svelte; /repositories?q=foo%28 also returned 500.

Proposed fix

This value is stateful history, not derived state. Store it with $state.raw and update it from a non-self-referential pre-effect:

let previousSearchResults = $state.raw<ApiSearchResults | null>(
  data.searchOutcome.kind === "success" ? data.searchOutcome.results : null,
);

$effect.pre(() => {
  if (data.searchOutcome.kind === "success") {
    previousSearchResults = data.searchOutcome.results;
  } else if (data.searchOutcome.kind === "none") {
    previousSearchResults = null;
  }
});

Apply the analogous change to previousListResults. This preserves the last successful results on errors, clears search results for "none", and safely initializes SSR. The issue’s suggested fix is therefore correct, but should cover both pages.

Regression coverage should exercise:

  1. valid → invalid: error shown, old results retained;
  2. invalid → valid: live results recover;
  3. direct invalid URL: no HTTP 500;
  4. valid → empty search: retained results cleared.

No files were changed.

do it

Implemented the fix in both search and repository search.

The retained results now use $state.raw updated by $effect.pre, avoiding recursive derived evaluation.

Verified:

  • yarn lint — passed
  • yarn vitest run — 26 tests passed
  • yarn build — passed
  • Browser checks on both pages:
    • Direct invalid query renders normally, not HTTP 500
    • Valid → invalid retains previous results without browser errors
    • Invalid → valid resumes live search without reload

Changes are local and uncommitted.

commit and push to a branch. do not open a PR.

Committed and pushed: