Skip to content

2.0.0-beta.4 createProjection being derived from createMemo can cause an infinite loop #2648

@DominicDolan

Description

@DominicDolan

Describe the bug

When a projection uses a memo which calls a Promise, there can sometimes be an infinite loop. The creation function passed to createProjection gets called repeatedly. It also happens for a derived createStore

I had a lot of trouble fully replicating this bug. There seems to be quite a few conditions for this bug to show itself:

  1. The projection needs to both read and write to the draft store that's passed to it, something like:
const items = createProjection((store) => {
  for (const item of items()) {
    if (store.at(-1) == null || store.at(-1).timestamp < item.timestamp) {
      store.unshift(item);
    }
  }
}, [] as { timestamp: number; id: string }[]);
  1. A certain number of array elements has to be affected for some reason. In the example above if you do push instead of unshift the looping doesn't appear.
  2. Similarly, if you use a small array like 3 or 4 items the loop doesn't appear. This made me think I was going mad
  3. If the projection function is async it's only half broken, the log output shows it repeats the function 363 times but eventually stops

Your Example Website or App

https://stackblitz.com/edit/github-evfywxxk-bmgpgugm?file=src%2Fmain.tsx

Steps to Reproduce the Bug or Issue

  1. Go to the above stackblitz example: https://stackblitz.com/edit/github-evfywxxk-bmgpgugm?file=src%2Fmain.tsx
  2. Open the console
  3. When it runs, the "creating store" log repeats forever
Image

Expected behavior

There should be no infinite loops

Screenshots or Videos

No response

Platform

  • OS: Linux
  • Browser: Chrome
  • Version: 146.0.7680.75

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions