### Start Svelte Development Server
Source: https://github.com/get-convex/convex-svelte/blob/main/README.md
Run this command after cloning the repository and installing dependencies to start a local development server for trying out the library.
```bash
npm run dev
```
--------------------------------
### Setup Convex Client in Svelte Layout
Source: https://context7.com/get-convex/convex-svelte/llms.txt
Initialize the Convex client in the root layout component. Ensure the PUBLIC_CONVEX_URL environment variable is set.
```svelte
{@render children()}
```
--------------------------------
### Install convex-svelte
Source: https://github.com/get-convex/convex-svelte/blob/main/README.md
Install the necessary Convex packages for your Svelte project.
```bash
npm install convex convex-svelte
```
--------------------------------
### Setup Convex in Svelte Layout
Source: https://github.com/get-convex/convex-svelte/blob/main/README.md
Call `setupConvex()` in a parent component to initialize the Convex client with your deployment URL. This should be done above components that require Convex functionality.
```svelte
```
--------------------------------
### Execute Convex Mutations with useConvexClient
Source: https://github.com/get-convex/convex-svelte/blob/main/README.md
Use `useConvexClient()` to get a client instance for executing mutations. The `client.mutation()` function sends data to your Convex backend. Ensure correct API paths and data structures are used.
```svelte
```
--------------------------------
### Build Production Showcase App
Source: https://github.com/get-convex/convex-svelte/blob/main/README.md
This command creates a production-ready build of the showcase application.
```bash
npm run build
```
--------------------------------
### Initialize Convex Client with setupConvex
Source: https://context7.com/get-convex/convex-svelte/llms.txt
Call setupConvex in a parent component to initialize the Convex client. It makes the client available to child components via Svelte's context API and handles cleanup.
```svelte
{@render children()}
```
--------------------------------
### Build Convex Svelte Library
Source: https://github.com/get-convex/convex-svelte/blob/main/README.md
Execute this command to build the Convex Svelte library during development.
```bash
npm run package
```
--------------------------------
### Use ConvexClient with useConvexClient
Source: https://context7.com/get-convex/convex-svelte/llms.txt
Use useConvexClient to access the ConvexClient instance for running mutations, actions, and managing authentication. Ensure setupConvex has been called in a parent component.
```svelte
```
--------------------------------
### Subscribe to Convex Queries with useQuery
Source: https://github.com/get-convex/convex-svelte/blob/main/README.md
Use the `useQuery()` hook to subscribe to data from Convex. It handles loading states, errors, and displays data, rendering updates automatically. The `useResultFromPreviousArguments` option can be useful for optimizing updates.
```svelte
...{#if query.isLoading}
Loading...
{:else if query.error != null}
failed to load: {query.error.toString()}
{:else}
{#each query.data as message}
{message.author}{message.body}
{/each}
{/if}
```
--------------------------------
### useQuery with Initial Data and Keep Previous Data Options
Source: https://context7.com/get-convex/convex-svelte/llms.txt
Use `initialData` for SSR hydration and `keepPreviousData` to show stale results during new data loading. This prevents a loading state on argument changes.
```svelte
{#if messages.data}
{#each messages.data as message}
{message.author}: {message.body}
{/each}
{/if}
```
--------------------------------
### Publish Library to npm
Source: https://github.com/get-convex/convex-svelte/blob/main/README.md
After updating the package name and license in `package.json`, use this command to publish your library to the npm registry.
```bash
npm publish
```
--------------------------------
### Subscribe to Convex Queries with useQuery
Source: https://context7.com/get-convex/convex-svelte/llms.txt
Use useQuery to subscribe to Convex queries, receiving reactive data, loading, error, and stale states. Supports reactive arguments via closures for dynamic subscriptions.
```svelte
{#if messages.isLoading}
Loading messages...
{:else if messages.error}
Error: {messages.error.message}
{:else}
{#each messages.data as message}
{message.author}: {message.body}
{/each}
{/if}
```
--------------------------------
### Deploy Svelte App with Convex Functions
Source: https://github.com/get-convex/convex-svelte/blob/main/README.md
Use this command in production build pipelines to build your Svelte app and deploy Convex functions. It specifies environment variables for the Convex URL and the build command.
```bash
npx convex deploy --cmd-url-env-var-name PUBLIC_CONVEX_URL --cmd 'npm run build'
```
--------------------------------
### Server-Side Rendering with initialData
Source: https://github.com/get-convex/convex-svelte/blob/main/README.md
Avoid initial loading states by providing `initialData` to `useQuery()`. Fetch data in a `+page.server.ts` file using `ConvexHttpClient` and pass it to the `initialData` option in the Svelte component.
```typescript
// +page.server.ts
import { ConvexHttpClient } from 'convex/browser';
import type { PageServerLoad } from './$types.js';
import { PUBLIC_CONVEX_URL } from '$env/static/public';
import { api } from '../convex/_generated/api.js';
export const load = (async () => {
const client = new ConvexHttpClient(PUBLIC_CONVEX_URL!)
return {
messages: await client.query(api.messages.list, { muteWords: [] })
};
}) satisfies PageServerLoad;
```
```svelte
```
--------------------------------
### Manually Set Convex Client Context
Source: https://context7.com/get-convex/convex-svelte/llms.txt
Manually set a `ConvexClient` instance in Svelte context for custom configuration or sharing an existing client. Includes custom authentication and cleanup on unmount.
```svelte
{@render children()}
```
--------------------------------
### Conditionally Skip useQuery
Source: https://context7.com/get-convex/convex-svelte/llms.txt
Skip query execution by returning 'skip' from the arguments function. `isLoading` will be false, `error` null, and `data` undefined when skipped. Useful for auth-dependent queries.
```svelte
{#if userProfile.isLoading}
Loading profile...
{:else if userProfile.error}
Error loading profile
{:else if userProfile.data}
Welcome, {userProfile.data.name}!
{:else}
Please log in to view your profile
{/if}
```
--------------------------------
### Real-time Chat Component with Convex Svelte
Source: https://context7.com/get-convex/convex-svelte/llms.txt
A Svelte component for a chat application using `useQuery` for real-time messages and `useConvexClient` for sending messages. Supports features like filtering, stale data display, and query skipping.
```svelte
{#if messages.isLoading}
Loading...
{:else if messages.error}
Failed to load: {messages.error.message}
{:else}
{#each messages.data as message}
{message.author}: {message.body}
{/each}
{/if}
```
--------------------------------
### Conditionally Skip Convex Queries
Source: https://github.com/get-convex/convex-svelte/blob/main/README.md
Skip a query by returning the string 'skip' from the arguments function. This is useful for queries dependent on conditions like authentication or user input. When skipped, `isLoading` is false, `error` is null, and `data` is undefined.
```svelte
{#if activeUserResponse.isLoading}
Loading user...
{:else if activeUserResponse.error}
Error: {activeUserResponse.error}
{:else if activeUserResponse.data}
Welcome, {activeUserResponse.data.name}!
{/if}
```
--------------------------------
### Use a Convex Query in React
Source: https://github.com/get-convex/convex-svelte/blob/main/src/convex/README.md
Call a Convex query function from a React component using the `useQuery` hook. Pass arguments as the second parameter.
```typescript
const data = useQuery(api.functions.myQueryFunction, {
first: 10,
second: 'hello'
});
```
--------------------------------
### Define a Convex Query Function
Source: https://github.com/get-convex/convex-svelte/blob/main/src/convex/README.md
Define a query function with argument validators and implement database reads. Use `v` for argument validation.
```typescript
// functions.js
import { query } from './_generated/server';
import { v } from 'convex/values';
export const myQueryFunction = query({
// Validators for arguments.
args: {
first: v.number(),
second: v.string()
},
// Function implementation.
handler: async (ctx, args) => {
// Read the database as many times as you need here.
// See https://docs.convex.dev/database/reading-data.
const documents = await ctx.db.query('tablename').collect();
// Arguments passed from the client are properties of the args object.
console.log(args.first, args.second);
// Write arbitrary JavaScript here: filter, aggregate, build derived data,
// remove non-public properties, or create new objects.
return documents;
}
});
```
--------------------------------
### Use a Convex Mutation in React
Source: https://github.com/get-convex/convex-svelte/blob/main/src/convex/README.md
Call a Convex mutation function from a React component using the `useMutation` hook. Mutations can be fired and forgotten or their results can be awaited.
```typescript
const mutation = useMutation(api.functions.myMutationFunction);
function handleButtonPress() {
// fire and forget, the most common way to use mutations
mutation({ first: 'Hello!', second: 'me' });
// OR
// use the result once the mutation has completed
mutation({ first: 'Hello!', second: 'me' }).then((result) => console.log(result));
}
```
--------------------------------
### Define a Convex Mutation Function
Source: https://github.com/get-convex/convex-svelte/blob/main/src/convex/README.md
Define a mutation function with argument validators for data manipulation. Mutations can also read from the database.
```typescript
// functions.js
import { mutation } from './_generated/server';
import { v } from 'convex/values';
export const myMutationFunction = mutation({
// Validators for arguments.
args: {
first: v.string(),
second: v.string()
},
// Function implementation.
handler: async (ctx, args) => {
// Insert or modify documents in the database here.
// Mutations can also read from the database like queries.
// See https://docs.convex.dev/database/writing-data.
const message = { body: args.first, author: args.second };
const id = await ctx.db.insert('messages', message);
// Optionally, return a value from your mutation.
return await ctx.db.get(id);
}
});
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.