Skip to content

Single flight mutation responds with stale data if query has been used inside command already #14832

@phi-bre

Description

@phi-bre

Describe the bug

If a command is specifically calling .refresh() on the server side of the remote function, the query will not actually be called again if it has been used in the command earlier.

export const getTodos = query(async () => {
  // returns todo list from database
});

export const addTodo = command(async () => {
  const previousTodos = await getTodos(); // !!! This call causes the issue.

  // Insert data into database that depends on the previous state:`New todo: ${previousTodos.length}`];

  await getTodos().refresh(); // Should force getTodos to rerun before responding with single flight mutation but responds with empty array.
});

I'd assume this is due to the caching mechanism of the query, and .refresh() reusing this stale state to respond in the single flight mutation instead of recomputing the function.

Reproduction

https://stackblitz.com/edit/sveltejs-kit-template-default-fydqb1te?file=src%2Flib%2Freproduction.remote.ts

Clicking on the Add todo button for the first time will not update the UI as the server responds with the stale data with no todos in the list.

Clicking again will render the state that should've rendered after the first click.

Logs

Network log:

{"type":"result","result":"-1","refreshes":"[{\"1chihuf/getTodos/\":1},[]]"}


Server logs:

getting todos
getting todos
adding todo


(there should be another "getting todos" log after adding todo if .refresh() actually worked)

System Info

System:
    OS: Linux 5.0 undefined
    CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 20.19.1 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 10.8.2 - /usr/local/bin/npm
    pnpm: 8.15.6 - /usr/local/bin/pnpm
  npmPackages:
    @sveltejs/adapter-auto: ^6.1.0 => 6.1.1 
    @sveltejs/kit: ^2.43.2 => 2.48.0 
    @sveltejs/vite-plugin-svelte: ^6.2.0 => 6.2.1 
    svelte: ^5.39.5 => 5.42.2 
    vite: ^7.1.7 => 7.1.1

Severity

serious, but I can work around it

Additional Information

You can get around this by moving the logic of the query out into a separate non-remote function, but this issue can sneak in by mistake quite quickly and looks like a client side reactivity issue on the surface.

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