Skip to content

Commit 97084a3

Browse files
Document initialData
1 parent e4e2b74 commit 97084a3

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

README.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,47 @@ Running a mutation looks like
8787
</form>
8888
```
8989

90+
### Server-side rendering
91+
92+
`useQuery()` accepts an `initialData` option in its third argument.
93+
By defining a `load()` function in a +page.server.ts file
94+
that uses the `ConvexHttpClient` to request the same query to get initial data
95+
and passing that through to the `initialData` option of a useQuery call you can avoid an initial loading state.
96+
97+
```ts
98+
// +page.server.ts
99+
import { ConvexHttpClient } from 'convex/browser';
100+
import type { PageServerLoad } from './$types.js';
101+
import { PUBLIC_CONVEX_URL } from '$env/static/public';
102+
import { api } from '../convex/_generated/api.js';
103+
104+
export const load = (async () => {
105+
const client = new ConvexHttpClient(PUBLIC_CONVEX_URL!);
106+
return {
107+
messages: await client.query(api.messages.list, { muteWords: [] })
108+
};
109+
}) satisfies PageServerLoad;
110+
```
111+
112+
```svelte
113+
<script lang="ts">
114+
// +page.svelte
115+
import type { PageData } from './$types.js';
116+
let { data }: { data: PageData } = $props();
117+
118+
import { useQuery, useConvexClient } from '$lib/client.svelte.js';
119+
import { api } from '../convex/_generated/api.js';
120+
121+
const messages = useQuery(
122+
api.messages.list,
123+
() => args,
124+
() => ({ initialData: data.messages })
125+
);
126+
</script>
127+
```
128+
129+
Combining specifying `initialData` and either setting the `keepPreviousData` option to true or never modifying the arguments passed to a query should be enough to avoid ever seeing a loading state for a `useQuery()`.
130+
90131
### Deploying a Svelte App
91132

92133
In production build pipelines use the build command

0 commit comments

Comments
 (0)