Unverified Commit dbc83344 authored by Thomas Ballinger's avatar Thomas Ballinger Committed by GitHub

chore(examples): Update convex example (#43741)

parent 8006dbc7
...@@ -20,28 +20,14 @@ yarn create next-app --example convex convex-app ...@@ -20,28 +20,14 @@ yarn create next-app --example convex convex-app
pnpm create next-app --example convex convex-app pnpm create next-app --example convex convex-app
``` ```
Log in to Convex, Run
```bash
npx convex login
```
initialize a new Convex project,
```bash
npx convex init
```
and then run the following two commands in two different terminals:
```bash
npx convex dev
```
```bash ```bash
npm run dev npm run dev
``` ```
to run `next dev` and a Convex file watcher at the same time. This command will log you into Convex, so you'll need to create a Convex account if this is your first project.
Once everything is working, commit your code and deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)). Once everything is working, commit your code and deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
Use `npx convex deploy && npm run build` as the build command and set the `CONVEX_DEPLOY_KEY` environmental variable in Vercel ([Documentation](https://docs.convex.dev/getting-started/deployment/hosting/vercel)). Use `npx convex deploy && npm run build` as the build command and set the `CONVEX_DEPLOY_KEY` environmental variable in Vercel ([Documentation](https://docs.convex.dev/getting-started/deployment/hosting/vercel)).
# Welcome to your Convex functions directory! # Welcome to your Convex functions directory!
Write your Convex functions here. Write your Convex functions here. See
https://docs.convex.dev/using/writing-convex-functions for more.
A query function looks like: A query function that takes two arguments looks like:
```typescript ```typescript
// myQueryFunction.ts // myQueryFunction.ts
import { query } from './_generated/server' import { query } from './_generated/server'
export default query(async ({ db }) => { export default query(async ({ db }, first: number, second: string) => {
// Load data with `db` here! // Validate arguments here.
if (typeof first !== 'number' || first < 0) {
throw new Error('First argument is not a non-negative number.')
}
if (typeof second !== 'string' || second.length > 1000) {
throw new Error('Second argument is not a string of length 1000 or less.')
}
// Query the database as many times as you need here.
// See https://docs.convex.dev/using/database-queries to learn how to write queries.
const documents = await db.query('tablename').collect()
// Write arbitrary JavaScript here: filter, aggregate, build derived data,
// remove non-public properties, or create new objects.
return documents
}) })
``` ```
Using this query function in a React component looks like:
```typescript
const data = useQuery('myQueryFunction', 10, 'hello')
```
A mutation function looks like: A mutation function looks like:
```typescript ```typescript
// myMutationFunction.ts // myMutationFunction.ts
import { mutation } from './_generated/server' import { mutation } from './_generated/server'
export default mutation(async ({ db }) => { export default mutation(async ({ db }, first: string, second: string) => {
// Edit data with `db` here! // Validate arguments here.
if (typeof first !== 'string' || typeof second !== 'string') {
throw new Error('Both arguments must be strings')
}
// Insert or modify documents in the database here.
// Mutations can also read from the database like queries.
const message = { body: first, author: second }
const id = await db.insert('messages', message)
// Optionally, return a value from your mutation.
return await db.get(id)
}) })
``` ```
Using this mutation function in a React component looks like:
```typescript
const mutation = useMutation('myMutationFunction')
function handleButtonPress() {
// fire and forget, the most common way to use mutations
mutation('Hello!', 'me')
// OR
// use the result once the mutation has completed
mutation('Hello!', 'me').then((result) => console.log(result))
}
```
The Convex CLI is your friend. See everything it can do by running The Convex CLI is your friend. See everything it can do by running
`npx convex -h` in your project root directory. To learn more, launch the docs `npx convex -h` in your project root directory. To learn more, launch the docs
with `npx convex docs`. with `npx convex docs`.
/* eslint-disable */
/**
* Generated API.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* Generated by convex@0.5.0.
* To regenerate, run `npx convex codegen`.
* @module
*/
import type { ApiFromModules } from "convex/api";
import type * as listMessages from "../listMessages";
import type * as sendMessage from "../sendMessage";
/**
* A type describing your app's public Convex API.
*
* This `API` type includes information about the arguments and return
* types of your app's query and mutation functions.
*
* This type should be used with type-parameterized classes like
* `ConvexReactClient` to create app-specific types.
*/
export type API = ApiFromModules<{
listMessages: typeof listMessages;
sendMessage: typeof sendMessage;
}>;
/* eslint-disable */
/**
* Generated development client configuration.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* Generated by convex@0.5.0.
* To regenerate, run `npx convex codegen`.
* @module
*/
import type { ClientConfiguration } from "convex/browser";
/**
* The DEV Convex client configuration.
*
* This configuration connects your client to your dev Convex deployment
* when `npx convex dev` is running.
*
* To generate the production version, run `npx convex deploy`.
*
* Usage:
*
* ```ts
* import clientConfig from "../convex/_generated/clientConfig";
*
* const convex = new ConvexReactClient(clientConfig);
* ```
*/
declare const clientConfig: ClientConfiguration;
export default clientConfig;
/* eslint-disable */
/**
* Generated development client configuration.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* Generated by convex@0.5.0.
* To regenerate, run `npx convex codegen`.
* @module
*/
/**
* The DEV Convex client configuration.
*
* This configuration connects your client to your dev Convex deployment
* when `npx convex dev` is running.
*
* To generate the production version, run `npx convex deploy`.
*
* Usage:
*
* ```ts
* import clientConfig from "../convex/_generated/clientConfig";
*
* const convex = new ConvexReactClient(clientConfig);
* ```
*/
const clientConfig = {
address: "http://localhost:8187",
};
export default clientConfig;
...@@ -4,34 +4,47 @@ ...@@ -4,34 +4,47 @@
* *
* THIS CODE IS AUTOMATICALLY GENERATED. * THIS CODE IS AUTOMATICALLY GENERATED.
* *
* Generated by convex@0.2.0. * Generated by convex@0.5.0.
* To regenerate, run `npx convex codegen`. * To regenerate, run `npx convex codegen`.
* @module * @module
*/ */
import { AnyDataModel } from "convex/server"; import type {
import { GenericId } from "convex/values"; DataModelFromSchemaDefinition,
DocumentMapFromSchemaDefinition,
} from "convex/schema";
import type { TableNamesInDataModel } from "convex/server";
import { GenericId, GenericIdConstructor } from "convex/values";
import schema from "../schema";
/** /**
* No `schema.ts` file found! * The names of all of your Convex tables.
*
* This generated code has permissive types like `Document = any` because
* Convex doesn't know your schema. If you'd like more type safety, see
* https://docs.convex.dev/using/schemas for instructions on how to add a
* schema file.
*
* After you write a schema, rerun codegen with `npx convex codegen`.
*/ */
export type TableNames = TableNamesInDataModel<DataModel>;
/** /**
* The names of all of your Convex tables. * The type of a document stored in Convex.
*
* @typeParam TableName - A string literal type of the table name (like "users").
*/ */
export type TableNames = string; export type Document<TableName extends TableNames> =
DocumentMapFromSchemaDefinition<typeof schema>[TableName];
/** /**
* The type of a document stored in Convex. * An identifier for a document in Convex.
*
* Convex documents are uniquely identified by their `Id`, which is accessible
* on the `_id` field. To learn more, see [Data Modeling](https://docs.convex.dev/using/data-modeling).
*
* Documents can be loaded using `db.get(id)` in query and mutation functions.
*
* **Important**: Use `myId.equals(otherId)` to check for equality.
* Using `===` will not work because two different instances of `Id` can refer
* to the same document.
*
* @typeParam TableName - A string literal type of the table name (like "users").
*/ */
export type Document = any; export type Id<TableName extends TableNames> = GenericId<TableName>;
/** /**
* An identifier for a document in Convex. * An identifier for a document in Convex.
...@@ -45,8 +58,7 @@ export type Document = any; ...@@ -45,8 +58,7 @@ export type Document = any;
* Using `===` will not work because two different instances of `Id` can refer * Using `===` will not work because two different instances of `Id` can refer
* to the same document. * to the same document.
*/ */
export type Id = GenericId<string>; export declare const Id: GenericIdConstructor<TableNames>;
export declare const Id: typeof GenericId;
/** /**
* A type describing your Convex data model. * A type describing your Convex data model.
...@@ -57,4 +69,4 @@ export declare const Id: typeof GenericId; ...@@ -57,4 +69,4 @@ export declare const Id: typeof GenericId;
* This type is used to parameterize methods like `queryGeneric` and * This type is used to parameterize methods like `queryGeneric` and
* `mutationGeneric` to make them type-safe. * `mutationGeneric` to make them type-safe.
*/ */
export type DataModel = AnyDataModel; export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
* *
* THIS CODE IS AUTOMATICALLY GENERATED. * THIS CODE IS AUTOMATICALLY GENERATED.
* *
* Generated by convex@0.2.0. * Generated by convex@0.5.0.
* To regenerate, run `npx convex codegen`. * To regenerate, run `npx convex codegen`.
* @module * @module
*/ */
......
...@@ -4,36 +4,21 @@ ...@@ -4,36 +4,21 @@
* *
* THIS CODE IS AUTOMATICALLY GENERATED. * THIS CODE IS AUTOMATICALLY GENERATED.
* *
* Generated by convex@0.2.0. * Generated by convex@0.5.0.
* To regenerate, run `npx convex codegen`. * To regenerate, run `npx convex codegen`.
* @module * @module
*/ */
import type { OptimisticLocalStore as GenericOptimisticLocalStore } from "convex/browser";
import type { import type {
ApiFromModules, UseActionForAPI,
OptimisticLocalStore as GenericOptimisticLocalStore,
} from "convex/browser";
import type {
UseQueryForAPI,
UseMutationForAPI,
UseConvexForAPI, UseConvexForAPI,
UsePaginatedQueryForAPI,
UseMutationForAPI,
UseQueriesForAPI,
UseQueryForAPI,
} from "convex/react"; } from "convex/react";
import type * as getCounter from "../getCounter"; import type { API } from "./api";
import type * as incrementCounter from "../incrementCounter";
/**
* A type describing your app's public Convex API.
*
* This `ConvexAPI` type includes information about the arguments and return
* types of your app's query and mutation functions.
*
* This type should be used with type-parameterized classes like
* `ConvexReactClient` to create app-specific types.
*/
export type ConvexAPI = ApiFromModules<{
getCounter: typeof getCounter;
incrementCounter: typeof incrementCounter;
}>;
/** /**
* Load a reactive query within a React component. * Load a reactive query within a React component.
...@@ -47,7 +32,7 @@ export type ConvexAPI = ApiFromModules<{ ...@@ -47,7 +32,7 @@ export type ConvexAPI = ApiFromModules<{
* @param args - The arguments to the query function. * @param args - The arguments to the query function.
* @returns `undefined` if loading and the query's return value otherwise. * @returns `undefined` if loading and the query's return value otherwise.
*/ */
export declare const useQuery: UseQueryForAPI<ConvexAPI>; export declare const useQuery: UseQueryForAPI<API>;
/** /**
* Construct a new {@link ReactMutation}. * Construct a new {@link ReactMutation}.
...@@ -65,7 +50,24 @@ export declare const useQuery: UseQueryForAPI<ConvexAPI>; ...@@ -65,7 +50,24 @@ export declare const useQuery: UseQueryForAPI<ConvexAPI>;
* @param name - The name of the mutation. * @param name - The name of the mutation.
* @returns The {@link ReactMutation} object with that name. * @returns The {@link ReactMutation} object with that name.
*/ */
export declare const useMutation: UseMutationForAPI<ConvexAPI>; export declare const useMutation: UseMutationForAPI<API>;
/**
* Construct a new {@link ReactAction}.
*
* Action objects can be called like functions to request execution of the
* corresponding Convex function.
*
* The value returned by this hook is stable across renders, so it can be used
* by React dependency arrays and memoization logic relying on object identity
* without causing rerenders.
*
* This relies on the {@link ConvexProvider} being above in the React component tree.
*
* @param name - The name of the action.
* @returns The {@link ReactAction} object with that name.
*/
export declare const useAction: UseActionForAPI<API>;
/** /**
* Get the {@link ConvexReactClient} within a React component. * Get the {@link ConvexReactClient} within a React component.
...@@ -74,10 +76,92 @@ export declare const useMutation: UseMutationForAPI<ConvexAPI>; ...@@ -74,10 +76,92 @@ export declare const useMutation: UseMutationForAPI<ConvexAPI>;
* *
* @returns The active {@link ConvexReactClient} object, or `undefined`. * @returns The active {@link ConvexReactClient} object, or `undefined`.
*/ */
export declare const useConvex: UseConvexForAPI<ConvexAPI>; export declare const useConvex: UseConvexForAPI<API>;
/**
* Load data reactively from a paginated query to a create a growing list.
*
* This can be used to power "infinite scroll" UIs.
*
* This hook must be used with Convex query functions that match
* {@link PaginatedQueryFunction}. This means they must:
* 1. Have a first argument must be an object containing `numItems` and `cursor`.
* 2. Return a {@link PaginationResult}.
*
* `usePaginatedQuery` concatenates all the pages
* of results into a single list and manages the continuation cursors when
* requesting more items.
*
* Example usage:
* ```typescript
* const { results, status, loadMore } = usePaginatedQuery(
* "listMessages",
* { initialNumItems: 5 },
* "#general"
* );
* ```
*
* @param name - The name of the query function.
* @param options - An object specifying the `initialNumItems` to be loaded in
* the first page.
* @param args - The arguments to the query function, excluding the first.
* @returns A {@link UsePaginatedQueryResult} that includes the currently loaded
* items, the status of the pagination, and a `loadMore` function.
*/
export declare const usePaginatedQuery: UsePaginatedQueryForAPI<API>;
/**
* Load a variable number of reactive Convex queries.
*
* `useQueries` is similar to {@link useQuery} but it allows
* loading multiple queries which can be useful for loading a dynamic number
* of queries without violating the rules of React hooks.
*
* This hook accepts an object whose keys are identifiers for each query and the
* values are objects of `{ name: string, args: Value[] }`. The `name` is the
* name of the Convex query function to load, and the `args` are the arguments to
* that function.
*
* The hook returns an object that maps each identifier to the result of the query,
* `undefined` if the query is still loading, or an instance of `Error` if the query
* threw an exception.
*
* For example if you loaded a query like:
* ```typescript
* const results = useQueriesGeneric({
* messagesInGeneral: {
* name: "listMessages",
* args: ["#general"]
* }
* });
* ```
* then the result would look like:
* ```typescript
* {
* messagesInGeneral: [{
* channel: "#general",
* body: "hello"
* _id: ...,
* _creationTime: ...
* }]
* }
* ```
*
* This React hook contains internal state that will cause a rerender
* whenever any of the query results change.
*
* Throws an error if not used under {@link ConvexProvider}.
*
* @param queries - An object mapping identifiers to objects of
* `{name: string, args: Value[] }` describing which query functions to fetch.
* @returns An object with the same keys as the input. The values are the result
* of the query function, `undefined` if it's still loading, or an `Error` if
* it threw an exception.
*/
export declare const useQueries: UseQueriesForAPI<API>;
/** /**
* A view of the query results currently in the Convex client for use within * A view of the query results currently in the Convex client for use within
* optimistic updates. * optimistic updates.
*/ */
export type OptimisticLocalStore = GenericOptimisticLocalStore<ConvexAPI>; export type OptimisticLocalStore = GenericOptimisticLocalStore<API>;
...@@ -4,15 +4,18 @@ ...@@ -4,15 +4,18 @@
* *
* THIS CODE IS AUTOMATICALLY GENERATED. * THIS CODE IS AUTOMATICALLY GENERATED.
* *
* Generated by convex@0.2.0. * Generated by convex@0.5.0.
* To regenerate, run `npx convex codegen`. * To regenerate, run `npx convex codegen`.
* @module * @module
*/ */
import { import {
useQueryGeneric,
useMutationGeneric,
useConvexGeneric, useConvexGeneric,
useActionGeneric,
useMutationGeneric,
usePaginatedQueryGeneric,
useQueriesGeneric,
useQueryGeneric,
} from "convex/react"; } from "convex/react";
/** /**
...@@ -47,6 +50,23 @@ export const useQuery = useQueryGeneric; ...@@ -47,6 +50,23 @@ export const useQuery = useQueryGeneric;
*/ */
export const useMutation = useMutationGeneric; export const useMutation = useMutationGeneric;
/**
* Construct a new {@link ReactAction}.
*
* Convex function objects can be called like functions to request execution of
* the corresponding Convex function.
*
* The value returned by this hook is stable across renders, so it can be used
* by React dependency arrays and memoization logic relying on object identity
* without causing rerenders.
*
* This relies on the {@link ConvexProvider} being above in the React component tree.
*
* @param name - The name of the function.
* @returns The {@link ReactAction} object with that name.
*/
export const useAction = useActionGeneric;
/** /**
* Get the {@link ConvexReactClient} within a React component. * Get the {@link ConvexReactClient} within a React component.
* *
...@@ -55,3 +75,92 @@ export const useMutation = useMutationGeneric; ...@@ -55,3 +75,92 @@ export const useMutation = useMutationGeneric;
* @returns The active {@link ConvexReactClient} object, or `undefined`. * @returns The active {@link ConvexReactClient} object, or `undefined`.
*/ */
export const useConvex = useConvexGeneric; export const useConvex = useConvexGeneric;
/**
* Load data reactively from a paginated query to a create a growing list.
*
* This can be used to power "infinite scroll" UIs.
*
* This hook must be used with Convex query functions that match
* {@link PaginatedQueryFunction}. This means they must:
* 1. Have a first argument must be an object containing `numItems` and `cursor`.
* 2. Return a {@link PaginationResult}.
*
* `usePaginatedQuery` concatenates all the pages
* of results into a single list and manages the continuation cursors when
* requesting more items.
*
* Example usage:
* ```typescript
* const { results, status, loadMore } = usePaginatedQuery(
* "listMessages",
* { initialNumItems: 5 },
* "#general"
* );
* ```
*
* If the query `name` or `args` change, the pagination state will be reset
* to the first page. Similarly, if any of the pages result in an InvalidCursor
* or QueryScannedTooManyDocuments error, the pagination state will also reset
* to the first page.
*
* To learn more about pagination, see [Paginated Queries](https://docs.convex.dev/using/pagination).
*
* @param name - The name of the query function.
* @param options - An object specifying the `initialNumItems` to be loaded in
* the first page.
* @param args - The arguments to the query function, excluding the first.
* @returns A {@link UsePaginatedQueryResult} that includes the currently loaded
* items, the status of the pagination, and a `loadMore` function.
*/
export const usePaginatedQuery = usePaginatedQueryGeneric;
/**
* Load a variable number of reactive Convex queries.
*
* `useQueries` is similar to {@link useQuery} but it allows
* loading multiple queries which can be useful for loading a dynamic number
* of queries without violating the rules of React hooks.
*
* This hook accepts an object whose keys are identifiers for each query and the
* values are objects of `{ name: string, args: Value[] }`. The `name` is the
* name of the Convex query function to load, and the `args` are the arguments to
* that function.
*
* The hook returns an object that maps each identifier to the result of the query,
* `undefined` if the query is still loading, or an instance of `Error` if the query
* threw an exception.
*
* For example if you loaded a query like:
* ```typescript
* const results = useQueriesGeneric({
* messagesInGeneral: {
* name: "listMessages",
* args: ["#general"]
* }
* });
* ```
* then the result would look like:
* ```typescript
* {
* messagesInGeneral: [{
* channel: "#general",
* body: "hello"
* _id: ...,
* _creationTime: ...
* }]
* }
* ```
*
* This React hook contains internal state that will cause a rerender
* whenever any of the query results change.
*
* Throws an error if not used under {@link ConvexProvider}.
*
* @param queries - An object mapping identifiers to objects of
* `{name: string, args: Value[] }` describing which query functions to fetch.
* @returns An object with the same keys as the input. The values are the result
* of the query function, `undefined` if it's still loading, or an `Error` if
* it threw an exception.
*/
export const useQueries = useQueriesGeneric;
...@@ -4,20 +4,23 @@ ...@@ -4,20 +4,23 @@
* *
* THIS CODE IS AUTOMATICALLY GENERATED. * THIS CODE IS AUTOMATICALLY GENERATED.
* *
* Generated by convex@0.2.0. * Generated by convex@0.5.0.
* To regenerate, run `npx convex codegen`. * To regenerate, run `npx convex codegen`.
* @module * @module
*/ */
import { import {
ActionBuilderForAPI,
MutationBuilderForDataModel, MutationBuilderForDataModel,
QueryBuilderForDataModel, QueryBuilderForDataModel,
ActionCtx as GenericActionCtx,
QueryCtx as GenericQueryCtx, QueryCtx as GenericQueryCtx,
MutationCtx as GenericMutationCtx, MutationCtx as GenericMutationCtx,
DatabaseReader as GenericDatabaseReader, DatabaseReader as GenericDatabaseReader,
DatabaseWriter as GenericDatabaseWriter, DatabaseWriter as GenericDatabaseWriter,
} from "convex/server"; } from "convex/server";
import { DataModel } from "./dataModel.js"; import type { DataModel } from "./dataModel.js";
import type { API } from "./api.js";
/** /**
* Define a query in this Convex app's public API. * Define a query in this Convex app's public API.
...@@ -39,6 +42,21 @@ export declare const query: QueryBuilderForDataModel<DataModel>; ...@@ -39,6 +42,21 @@ export declare const query: QueryBuilderForDataModel<DataModel>;
*/ */
export declare const mutation: MutationBuilderForDataModel<DataModel>; export declare const mutation: MutationBuilderForDataModel<DataModel>;
/**
* Define an action in this Convex app's public API.
*
* An action is a function which can execute any JavaScript code, including non-deterministic
* code and code with side-effects. Actions are often used to call into third-party services.
* Actions execute in a Node.js environment and can interact with the database indirectly by
* calling queries and mutations via the provided `dbFunctions` object. Actions need to be defined
* in the `/convex/actions directory`. Queries and mutations, on the other hand, must be defined
* outside of the `/convex/actions directory`.
*
* @param func - The action. It receives a {@link ActionCtx} as its first argument.
* @returns The wrapped action. Include this as an `export` to name it and make it accessible.
*/
export declare const action: ActionBuilderForAPI<API>;
/** /**
* A set of services for use within Convex query functions. * A set of services for use within Convex query functions.
* *
...@@ -58,6 +76,14 @@ export type QueryCtx = GenericQueryCtx<DataModel>; ...@@ -58,6 +76,14 @@ export type QueryCtx = GenericQueryCtx<DataModel>;
*/ */
export type MutationCtx = GenericMutationCtx<DataModel>; export type MutationCtx = GenericMutationCtx<DataModel>;
/**
* A set of services for use within Convex mutation functions.
*
* The mutation context is passed as the first argument to any Convex mutation
* function run on the server.
*/
export type ActionCtx = GenericActionCtx<API>;
/** /**
* An interface to read from the database within Convex query functions. * An interface to read from the database within Convex query functions.
* *
......
...@@ -4,12 +4,12 @@ ...@@ -4,12 +4,12 @@
* *
* THIS CODE IS AUTOMATICALLY GENERATED. * THIS CODE IS AUTOMATICALLY GENERATED.
* *
* Generated by convex@0.2.0. * Generated by convex@0.5.0.
* To regenerate, run `npx convex codegen`. * To regenerate, run `npx convex codegen`.
* @module * @module
*/ */
import { queryGeneric, mutationGeneric } from "convex/server"; import { actionGeneric, queryGeneric, mutationGeneric } from "convex/server";
/** /**
* Define a query in this Convex app's public API. * Define a query in this Convex app's public API.
...@@ -30,3 +30,16 @@ export const query = queryGeneric; ...@@ -30,3 +30,16 @@ export const query = queryGeneric;
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/ */
export const mutation = mutationGeneric; export const mutation = mutationGeneric;
/**
* Define a function in this Convex app's public API.
*
* This is a generic function which unlike queries and mutations can execute any
* JavaScript code. Node functions execute in a Node.js environment and can
* interact with the database by calling queries and mutations via the provided
* convex object. Node functions need to be defined in /convex/node directory.
*
* @param func - The function. It receives a {@link ActionCtx} as its first argument.
* @returns The wrapped function. Include this as an `export` to name it and make it accessible.
*/
export const action = actionGeneric;
import { query } from './_generated/server'
export default query(async ({ db }, counterName: string): Promise<number> => {
const counterDoc = await db
.query('counter_table')
.filter((q) => q.eq(q.field('name'), counterName))
.first()
console.log('Got stuff')
if (counterDoc === null) {
return 0
}
return counterDoc.counter
})
import { mutation } from './_generated/server'
export default mutation(
async ({ db }, counterName: string, increment: number) => {
const counterDoc = await db
.query('counter_table')
.filter((q) => q.eq(q.field('name'), counterName))
.first()
if (counterDoc === null) {
db.insert('counter_table', {
name: counterName,
counter: increment,
})
// console.log messages appear in your browser's console and the Convex dashboard.
console.log('Created counter.')
} else {
counterDoc.counter += increment
db.replace(counterDoc._id, counterDoc)
console.log(`Value of counter is now ${counterDoc.counter}.`)
}
}
)
import { query } from './_generated/server'
import { Document } from './_generated/dataModel'
export default query(async ({ db }): Promise<Document<'messages'>[]> => {
return await db.query('messages').collect()
})
import { defineSchema, defineTable, s } from 'convex/schema'
export default defineSchema({
messages: defineTable({
author: s.string(),
body: s.string(),
}),
})
import { mutation } from './_generated/server'
export default mutation(async ({ db }, body: string, author: string) => {
const message = { body, author }
await db.insert('messages', message)
})
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
/* These compiler options are required by Convex */ /* These compiler options are required by Convex */
"target": "ESNext", "target": "ESNext",
"lib": ["ES2021"], "lib": ["ES2021", "dom"],
"forceConsistentCasingInFileNames": true, "forceConsistentCasingInFileNames": true,
"allowSyntheticDefaultImports": true, "allowSyntheticDefaultImports": true,
"module": "ESNext", "module": "ESNext",
...@@ -20,9 +20,6 @@ ...@@ -20,9 +20,6 @@
/* Prevents node_modules from adding additional global types e.g. node types */ /* Prevents node_modules from adding additional global types e.g. node types */
"types": [] "types": []
}, },
"include": [ "include": ["./**/*"],
"./**/*", "exclude": ["./_generated", "./actions"]
"../node_modules/convex/dist/esm/environment/index.d.ts"
],
"exclude": ["./_generated"]
} }
{ {
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "npm-run-all init dev:init --parallel dev:server dev:client",
"build": "next build", "build": "tsc && next build",
"init": "convex init",
"dev:server": "convex dev",
"dev:client": "next dev",
"dev:init": "convex dev --once",
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
...@@ -15,6 +19,7 @@ ...@@ -15,6 +19,7 @@
"@types/node": "~16.11.12", "@types/node": "~16.11.12",
"@types/react": "17.0.45", "@types/react": "17.0.45",
"@types/react-dom": "17.0.17", "@types/react-dom": "17.0.17",
"npm-run-all": "^4.1.5",
"prettier": "^2.7.1", "prettier": "^2.7.1",
"typescript": "^4.7.3" "typescript": "^4.7.3"
} }
......
import type { NextPage } from 'next' import { FormEvent, useEffect, useState } from 'react'
import Head from 'next/head' import { useMutation, useQuery } from '../convex/_generated/react'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import { useQuery, useMutation } from '../convex/_generated/react'
import { useCallback } from 'react'
const Home: NextPage = () => { export default function App() {
const counter = useQuery('getCounter', 'clicks') ?? 0 const messages = useQuery('listMessages') || []
const increment = useMutation('incrementCounter')
const incrementByOne = useCallback(() => increment('clicks', 1), [increment])
return ( const [newMessageText, setNewMessageText] = useState('')
<div className={styles.container}> const sendMessage = useMutation('sendMessage')
<Head>
<title>Next.js with Convex</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}> const [name, setName] = useState('user')
<h1 className={styles.title}>
Welcome to <a href="https://nextjs.org">Next.js</a> with{' '}
<a href="https://convex.dev">Convex</a>
</h1>
<p className={styles.description}> useEffect(() => {
{"Here's the counter:"} {counter} setName('User ' + Math.floor(Math.random() * 10000))
</p> }, [])
<button className={styles.button} onClick={incrementByOne}>
Add One!
</button>
</main>
<footer className={styles.footer}> async function handleSendMessage(event: FormEvent) {
<a event.preventDefault()
href="https://www.convex.dev/" setNewMessageText('')
target="_blank" await sendMessage(newMessageText, name)
rel="noopener noreferrer" }
> return (
Powered by{' '} <main>
<span className={styles.logo}> <h1>Convex Chat</h1>
<Image src="/convex.svg" alt="Convex Logo" width={90} height={18} /> <p className="badge">
</span> <span>{name}</span>
</a> </p>
</footer> <ul>
</div> {messages.map((message) => (
<li key={message._id.toString()}>
<span>{message.author}:</span>
<span>{message.body}</span>
<span>{new Date(message._creationTime).toLocaleTimeString()}</span>
</li>
))}
</ul>
<form onSubmit={handleSendMessage}>
<input
value={newMessageText}
onChange={(event) => setNewMessageText(event.target.value)}
placeholder="Write a message…"
/>
<input type="submit" value="Send" disabled={!newMessageText} />
</form>
</main>
) )
} }
export default Home
.container {
padding: 0 2rem;
display: flex;
flex-direction: column;
min-height: 100vh;
}
.main {
padding: 4rem 0;
flex: 10;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.button {
font-size: 1rem;
font-weight: 800;
cursor: pointer;
margin: 0.5rem;
padding: 0.5rem;
text-align: left;
text-decoration: none;
border: 1px solid #eaeaea;
border-radius: 10px;
transition: color 0.15s ease, border-color 0.15s ease;
text-align: center;
width: 200px;
}
.button:hover,
.button:focus,
.button:active {
color: #0070f3;
border-color: #0070f3;
}
.footer {
display: flex;
flex: 1;
padding: 2rem 0;
border-top: 1px solid #eaeaea;
justify-content: center;
align-items: center;
}
.footer a {
display: flex;
justify-content: center;
align-items: center;
flex-grow: 1;
}
.title a {
color: #0070f3;
text-decoration: none;
}
.title a:hover,
.title a:focus,
.title a:active {
text-decoration: underline;
}
.title {
margin: 0;
line-height: 1.15;
font-size: 3rem;
}
.title,
.description {
text-align: center;
}
.description {
margin: 2rem 0;
line-height: 1.5;
font-size: 1.5rem;
}
.logo {
height: 1em;
margin-left: 0.5rem;
}
.loadingLayout {
display: flex;
height: 100vh;
}
.loading,
.loading:after {
border-radius: 50%;
width: 5em;
height: 5em;
}
.loading {
margin: auto auto;
border: 0.8em solid #f4e9f1;
border-left: 0.8em solid #8d2676;
animation: load8 1.1s infinite linear;
}
@keyframes load8 {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
html, /* reset */
body { * {
padding: 0;
margin: 0; margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, padding: 0;
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; border: 0;
line-height: 1.5;
} }
a { body {
color: inherit; font-family: system-ui, 'Segoe UI', Roboto, 'Helvetica Neue', helvetica,
text-decoration: none; sans-serif;
} }
* { main {
box-sizing: border-box; padding-top: 1em;
padding-bottom: 1em;
width: min(800px, 95vw);
margin: 0 auto;
}
h1 {
text-align: center;
margin-bottom: 8px;
font-size: 1.8em;
font-weight: 500;
}
.badge {
text-align: center;
margin-bottom: 16px;
}
.badge span {
background-color: #212529;
color: #ffffff;
border-radius: 6px;
font-weight: bold;
padding: 4px 8px 4px 8px;
font-size: 0.75em;
}
ul {
margin: 8px;
border-radius: 8px;
border: solid 1px lightgray;
box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}
ul:empty {
display: none;
}
li {
display: flex;
justify-content: flex-start;
padding: 8px 16px 8px 16px;
border-bottom: solid 1px lightgray;
font-size: 16px;
}
li:last-child {
border: 0;
}
li span:nth-child(1) {
font-weight: bold;
margin-right: 4px;
white-space: nowrap;
}
li span:nth-child(2) {
margin-right: 4px;
word-break: break-word;
}
li span:nth-child(3) {
color: #6c757d;
margin-left: auto;
white-space: nowrap;
}
form {
display: flex;
justify-content: center;
}
input:not([type]) {
padding: 6px 12px 6px 12px;
color: rgb(33, 37, 41);
border: solid 1px rgb(206, 212, 218);
border-radius: 8px;
font-size: 16px;
}
input[type='submit'],
button {
margin-left: 4px;
background: lightblue;
color: white;
padding: 6px 12px 6px 12px;
border-radius: 8px;
font-size: 16px;
background-color: rgb(49, 108, 244);
}
input[type='submit']:hover,
button:hover {
background-color: rgb(41, 93, 207);
}
input[type='submit']:disabled,
button:disabled {
background-color: rgb(122, 160, 248);
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment