Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/social-hats-hope.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

fix: add type definitions for `query.set()` method to override the value of a remote query function
29 changes: 26 additions & 3 deletions documentation/docs/20-core-concepts/60-remote-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,17 +160,40 @@ export const getPost = query(v.string(), async (slug) => {

Both the argument and the return value are serialized with [devalue](https://github.com/sveltejs/devalue), which handles types like `Date` and `Map` (and custom types defined in your [transport hook](hooks#Universal-hooks-transport)) in addition to JSON.

### Refreshing queries
### Updating queries

Any query can be updated via its `refresh` method:
Any query can be re-fetched via its `refresh` method, which retrieves the latest value from the server:

```svelte
<button onclick={() => getPosts().refresh()}>
Check for new posts
</button>
```

> [!NOTE] Queries are cached while they're on the page, meaning `getPosts() === getPosts()`. This means you don't need a reference like `const posts = getPosts()` in order to refresh the query.
Alternatively, if you need to update its value manually, you can use the `set` method:

```svelte
<script>
import { getPosts } from './data.remote';
import { onMount } from 'svelte';

onMount(() => {
const ws = new WebSocket('/ws');
ws.addEventListener('message', (ev) => {
const message = JSON.parse(ev.data);
if (message.type === 'new-post') {
getPosts().set([
message.post,
...getPosts().current,
]);
}
});
return () => ws.close();
});
</script>
```

> [!NOTE] Queries are cached while they're on the page, meaning `getPosts() === getPosts()`. This means you don't need a reference like `const posts = getPosts()` in order to update the query.

## form

Expand Down
6 changes: 6 additions & 0 deletions packages/kit/src/exports/public.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1802,6 +1802,12 @@ export type RemoteResource<T> = Promise<Awaited<T>> & {
);

export type RemoteQuery<T> = RemoteResource<T> & {
/**
* On the client, this function will update the value of the query without re-fetching it.
*
* On the server, this throws an error.
*/
set(value: T): void;
/**
* On the client, this function will re-fetch the query from the server.
*
Expand Down
4 changes: 4 additions & 0 deletions packages/kit/src/runtime/app/server/remote/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ export function query(validate_or_fn, maybe_fn) {

promise.catch(() => {});

promise.set = () => {
throw new Error(`Cannot call '${__.name}.set()' on the server`);
};

promise.refresh = async () => {
const { state } = get_request_store();
const refreshes = state.refreshes;
Expand Down
2 changes: 2 additions & 0 deletions packages/kit/test/apps/basics/src/routes/remote/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@

<button onclick={() => count.refresh()} id="refresh-btn">Refresh</button>

<button onclick={() => count.set(999)} id="set-btn">Set</button>

<button
onclick={async () => {
command_result = await set_count({ c: 2 });
Expand Down
10 changes: 10 additions & 0 deletions packages/kit/test/apps/basics/test/client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1308,7 +1308,7 @@
expect(page.locator('p.loadingfail')).toBeHidden();
});

test('Catches fetch errors from server load functions (direct hit)', async ({ page }) => {

Check warning on line 1311 in packages/kit/test/apps/basics/test/client.test.js

View workflow job for this annotation

GitHub Actions / test-kit (18, ubuntu-latest, chromium)

flaky test: Catches fetch errors from server load functions (direct hit)

retries: 2

Check warning on line 1311 in packages/kit/test/apps/basics/test/client.test.js

View workflow job for this annotation

GitHub Actions / test-kit (20, ubuntu-latest, chromium)

flaky test: Catches fetch errors from server load functions (direct hit)

retries: 2

Check warning on line 1311 in packages/kit/test/apps/basics/test/client.test.js

View workflow job for this annotation

GitHub Actions / test-kit (22, ubuntu-latest, chromium)

flaky test: Catches fetch errors from server load functions (direct hit)

retries: 2
page.goto('/streaming/server-error');
await expect(page.locator('p.eager')).toHaveText('eager');
await expect(page.locator('p.fail')).toHaveText('fail');
Expand Down Expand Up @@ -1660,6 +1660,16 @@
}
});

test('query.set works', async ({ page }) => {
await page.goto('/remote');
let request_count = 0;
page.on('request', (r) => (request_count += r.url().includes('/_app/remote') ? 1 : 0));

await page.click('#set-btn');
await expect(page.locator('#count-result')).toHaveText('999 / 999 (false)');
expect(request_count).toBe(0);
});

test('hydrated data is reused', async ({ page }) => {
let request_count = 0;
page.on('request', (r) => (request_count += r.url().includes('/_app/remote') ? 1 : 0));
Expand Down
6 changes: 6 additions & 0 deletions packages/kit/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1778,6 +1778,12 @@ declare module '@sveltejs/kit' {
);

export type RemoteQuery<T> = RemoteResource<T> & {
/**
* On the client, this function will update the value of the query without re-fetching it.
*
* On the server, this throws an error.
*/
set(value: T): void;
/**
* On the client, this function will re-fetch the query from the server.
*
Expand Down
Loading