Subscriptions & Deep Loading
Jazz's Collaborative Values (such as CoMaps or CoLists) work like reactive state. By subscribing to them, you can react to both local and remote updates. This is the main way to consume data in your application.
Subscriptions also take care of loading CoValues that are not yet loaded locally and can do so deeply — by resolving nested CoValues. To make use of this, we'll show you how to specify the depth of data you need with resolve queries.
With each update you can also handle loading states and inaccessible CoValues.
Manual subscriptions
You can subscribe to a CoValue from anywhere in your code (if you have its ID) by using CoValue.subscribe()
.
Note: Unless you're using vanilla JavaScript, this is only used outside of React components - for example in server-side code or in tests. See the section below for convenient subscription hooks that you typically use in React.
class
class Task
Task extendsclass CoMap
CoMaps are collaborative versions of plain objects, mapping string-like keys to values.CoMap {Task.title: co<string>
title =co.
const co: { string: co<string>; number: co<number>; boolean: co<boolean>; null: co<null>; Date: co<Date>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number]>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T>; encoded<T>(arg: Encoder<T>): co<T>; ref: { ...; }; items: ItemsSym; optional: { ref: <C extends CoValueClass>(arg: C | ((_raw: InstanceType<C>["_raw"]) => C)) => co<InstanceType<C> | null | undefined>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T | undefined>; encoded<T>(arg: OptionalEncoder<T>): co<T | undefined>; string: co<string | undefined>; number: co<number | undefined>; boolean: co<boolean | undefined>; null: co<null | undefined>; Date: co<Date | undefined>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number] | undefined>; }; }
string: co<string>
string;Task.description: co<string>
description =co.
const co: { string: co<string>; number: co<number>; boolean: co<boolean>; null: co<null>; Date: co<Date>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number]>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T>; encoded<T>(arg: Encoder<T>): co<T>; ref: { ...; }; items: ItemsSym; optional: { ref: <C extends CoValueClass>(arg: C | ((_raw: InstanceType<C>["_raw"]) => C)) => co<InstanceType<C> | null | undefined>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T | undefined>; encoded<T>(arg: OptionalEncoder<T>): co<T | undefined>; string: co<string | undefined>; number: co<number | undefined>; boolean: co<boolean | undefined>; null: co<null | undefined>; Date: co<Date | undefined>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number] | undefined>; }; }
string: co<string>
string;Task.status: co<"todo" | "in-progress" | "completed">
status =co.
const co: { string: co<string>; number: co<number>; boolean: co<boolean>; null: co<null>; Date: co<Date>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number]>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T>; encoded<T>(arg: Encoder<T>): co<T>; ref: { ...; }; items: ItemsSym; optional: { ref: <C extends CoValueClass>(arg: C | ((_raw: InstanceType<C>["_raw"]) => C)) => co<InstanceType<C> | null | undefined>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T | undefined>; encoded<T>(arg: OptionalEncoder<T>): co<T | undefined>; string: co<string | undefined>; number: co<number | undefined>; boolean: co<boolean | undefined>; null: co<null | undefined>; Date: co<Date | undefined>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number] | undefined>; }; }
literal<["todo", "in-progress", "completed"]>(_lit_0: "todo", _lit_1: "in-progress", _lit_2: "completed"): co<"todo" | "in-progress" | "completed">
literal("todo", "in-progress", "completed");Task.assignedTo: co<string | undefined>
assignedTo =co.
const co: { string: co<string>; number: co<number>; boolean: co<boolean>; null: co<null>; Date: co<Date>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number]>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T>; encoded<T>(arg: Encoder<T>): co<T>; ref: { ...; }; items: ItemsSym; optional: { ref: <C extends CoValueClass>(arg: C | ((_raw: InstanceType<C>["_raw"]) => C)) => co<InstanceType<C> | null | undefined>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T | undefined>; encoded<T>(arg: OptionalEncoder<T>): co<T | undefined>; string: co<string | undefined>; number: co<number | undefined>; boolean: co<boolean | undefined>; null: co<null | undefined>; Date: co<Date | undefined>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number] | undefined>; }; }
optional.
optional: { ref: <C extends CoValueClass>(arg: C | ((_raw: InstanceType<C>["_raw"]) => C)) => co<InstanceType<C> | null | undefined>; ... 7 more ...; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number] | undefined>; }
string: co<string | undefined>
string; } // ... // Subscribe to a Task by ID constconst unsubscribe: () => void
unsubscribe =class Task
Task.CoMap.subscribe<Task, true>(this: CoValueClass<Task>, id: ID<Task>, listener: (value: Task, unsubscribe: () => void) => void): () => void (+1 overload)
Load and subscribe to a `CoMap` with a given ID, as a given account. Automatically also subscribes to updates to all referenced/nested CoValues as soon as they are accessed in the listener. `depth` specifies which (if any) fields that reference other CoValues to load as well before calling `listener` for the first time. The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth. You can pass `[]` or `{}` for shallowly loading only this CoMap, or `{ fieldA: depthA, fieldB: depthB }` for recursively loading referenced CoValues. Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest. Returns an unsubscribe function that you should call when you no longer need updates. Also see the `useCoState` hook to reactively subscribe to a CoValue in a React component.subscribe(const taskId: ID<Task>
taskId, (updatedTask: Task
updatedTask) => {var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without calling `require('console')`. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information.log("Task updated:",updatedTask: Task
updatedTask.Task.title: co<string>
title);var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without calling `require('console')`. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information.log("New status:",updatedTask: Task
updatedTask.Task.status: co<"todo" | "in-progress" | "completed">
status); }); // Clean up when you're doneconst unsubscribe: () => void
unsubscribe();
If you already have a CoValue instance, you can subscribe to it by calling its subscribe
method.
const
const task: Task
task =class Task
Task.
CoMap.create<Task>(this: CoValueClass<...>, init: { title: co<string> & (co<string> | undefined); description: co<string> & (co<string> | undefined); status: co<"todo" | "in-progress" | "completed"> & (co<...> | undefined); assignedTo?: string | ... 2 more ... | undefined; }, options?: { owner: Account | Group; unique?: CoValueUniqueness["uniqueness"]; } | Account | Group): Task
Create a new CoMap with the given initial values and owner. The owner (a Group or Account) determines access rights to the CoMap. The CoMap will immediately be persisted and synced to connected peers.create({title: co<string> & (co<string> | undefined)
title: "Cut the grass", ...const otherProps: any
otherProps }); constconst unsubscribe: () => void
unsubscribe =const task: Task
task.CoMap.subscribe<Task, true>(this: Task, listener: (value: Task, unsubscribe: () => void) => void): () => void (+1 overload)
Given an already loaded `CoMap`, subscribe to updates to the `CoMap` and ensure that the specified fields are loaded to the specified depth. Works like `CoMap.subscribe()`, but you don't need to pass the ID or the account to load as again. Returns an unsubscribe function that you should call when you no longer need updates.subscribe((updatedTask: Task
updatedTask) => {var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without calling `require('console')`. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information.log("Task updated:",updatedTask: Task
updatedTask.Task.title: co<string>
title); }); // Clean up when you're doneconst unsubscribe: () => void
unsubscribe();
Subscription hooks
useCoState
Jazz provides a useCoState
hook that provides a convenient way to subscribe to CoValues and handle loading states:
import {
useCoState } from "jazz-react"; function
function useCoState<V extends CoValue, const R extends RefsToResolve<V> = true>(Schema: CoValueClass<V>, id: ID<CoValue> | undefined, options?: { resolve?: RefsToResolveStrict<V, R>; }): Resolved<V, R> | undefined | null
GardenPlanner({
function GardenPlanner({ projectId }: { projectId: ID<Project>; }): "Project not found or not accessible" | "Loading project ..." | React.JSX.Element
projectId: ID<Project>
projectId }: {projectId: ID<Project>
projectId:type ID<T> = `co_z${string}` & IDMarker<T>
IDs are unique identifiers for `CoValue`s. Can be used with a type argument to refer to a specific `CoValue` type.ID<class Project
Project> }) { // Subscribe to a project and its tasks constproject =
const project: ({ tasks: Task[] & ListOfTasks; } & Project) | null | undefined
useCoState(
useCoState<Project, { tasks: { $each: boolean; }; }>(Schema: CoValueClass<Project>, id: ID<CoValue> | undefined, options?: { resolve?: RefsToResolve<Project, 10, []> | undefined; } | undefined): ({ ...; } & Project) | ... 1 more ... | undefined
class Project
Project,projectId: ID<Project>
projectId, {resolve?: RefsToResolve<Project, 10, []> | undefined
resolve: {tasks?: RefsToResolve<ListOfTasks, 10, [0]> | undefined
tasks: {$each: RefsToResolve<Task, 10, [0, 0]>
$each: true }, }, }); if (!project) { return
const project: ({ tasks: Task[] & ListOfTasks; } & Project) | null | undefined
const project: null | undefined
project === null ? "Project not found or not accessible" : "Loading project ..."; } return ( <JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div> <JSX.IntrinsicElements.h1: React.DetailedHTMLProps<React.HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>
h1>{project.
const project: { tasks: Task[] & ListOfTasks; } & Project
Project.name: co<string>
name}</JSX.IntrinsicElements.h1: React.DetailedHTMLProps<React.HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>
h1> <TaskList
function TaskList({ tasks }: { tasks: Task[]; }): React.JSX.Element
tasks: Task[]
tasks={project.
const project: { tasks: Task[] & ListOfTasks; } & Project
Project.tasks: Task[] & ListOfTasks & co<ListOfTasks | null>
tasks} /> </JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div> ); } functionTaskList({
function TaskList({ tasks }: { tasks: Task[]; }): React.JSX.Element
tasks: Task[]
tasks }: {tasks: Task[]
tasks:class Task
Task[] }) { return ( <JSX.IntrinsicElements.ul: React.DetailedHTMLProps<React.HTMLAttributes<HTMLUListElement>, HTMLUListElement>
ul> {tasks: Task[]
tasks.Array<Task>.map<React.JSX.Element>(callbackfn: (value: Task, index: number, array: Task[]) => React.JSX.Element, thisArg?: any): React.JSX.Element[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.map((task: Task
task) => ( <JSX.IntrinsicElements.li: React.DetailedHTMLProps<React.LiHTMLAttributes<HTMLLIElement>, HTMLLIElement>
liReact.Attributes.key?: React.Key | null | undefined
key={task: Task
task.CoMap.id: ID<Task>
The ID of this `CoMap`id}> <JSX.IntrinsicElements.span: React.DetailedHTMLProps<React.HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>
span>{task: Task
task.Task.title: co<string>
title}</JSX.IntrinsicElements.span: React.DetailedHTMLProps<React.HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>
span> <JSX.IntrinsicElements.span: React.DetailedHTMLProps<React.HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>
span>{task: Task
task.Task.status: co<"todo" | "in-progress" | "completed">
status}</JSX.IntrinsicElements.span: React.DetailedHTMLProps<React.HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>
span> </JSX.IntrinsicElements.li: React.DetailedHTMLProps<React.LiHTMLAttributes<HTMLLIElement>, HTMLLIElement>
li> ))} </JSX.IntrinsicElements.ul: React.DetailedHTMLProps<React.HTMLAttributes<HTMLUListElement>, HTMLUListElement>
ul> ); }
The useCoState
hook handles subscribing when the component mounts and unsubscribing when it unmounts, making it easy to keep your UI in sync with the underlying data.
useAccount
useAccount
is used to access the current user's account.
You can use this at the top-level of your app to subscribe to the current user's account profile and root.
Like useCoState
, you can specify a resolve query to also subscribe to CoValues referenced in the account profile or root.
import {
useAccount } from "jazz-react"; function
function useAccount<A extends RegisteredAccount>(): { me: A; logOut: () => void; } (+1 overload)
function ProjectList(): React.JSX.Element
ProjectList() { const {me } =
const me: ({ profile: Profile; root: { myProjects: (Project & { tasks: ListOfTasks; })[] & ListOfProjects; } & AccountRoot; } & MyAppAccount) | null | undefined
useAccount({
useAccount<MyAppAccount, { profile: true; root: { myProjects: { $each: { tasks: true; }; }; }; }>(options?: { resolve?: RefsToResolve<MyAppAccount, 10, []> | undefined; } | undefined): { ...; } (+1 overload)
resolve?: RefsToResolve<MyAppAccount, 10, []> | undefined
resolve: {profile?: RefsToResolve<Profile, 10, [0]> | undefined
profile: true,root?: RefsToResolve<AccountRoot, 10, [0]> | undefined
root: {myProjects?: RefsToResolve<ListOfProjects, 10, [0, 0]> | undefined
myProjects: {$each: RefsToResolve<Project, 10, [0, 0, 0]>
$each: {tasks?: RefsToResolve<ListOfTasks, 10, [0, 0, 0, 0]> | undefined
tasks: true } } }, }, }); if (!me) { return <
const me: ({ profile: Profile; root: { myProjects: (Project & { tasks: ListOfTasks; })[] & ListOfProjects; } & AccountRoot; } & MyAppAccount) | null | undefined
JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div>Loading...</JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div>; } return <JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div> <JSX.IntrinsicElements.h1: React.DetailedHTMLProps<React.HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>
h1>{me.
const me: { profile: Profile; root: { myProjects: (Project & { tasks: ListOfTasks; })[] & ListOfProjects; } & AccountRoot; } & MyAppAccount
Account.profile: Profile
profile.Profile.name: co<string>
name}'s projects</JSX.IntrinsicElements.h1: React.DetailedHTMLProps<React.HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>
h1> <JSX.IntrinsicElements.ul: React.DetailedHTMLProps<React.HTMLAttributes<HTMLUListElement>, HTMLUListElement>
ul> {me.
const me: { profile: Profile; root: { myProjects: (Project & { tasks: ListOfTasks; })[] & ListOfProjects; } & AccountRoot; } & MyAppAccount
root.
MyAppAccount.root: { myProjects: (Project & { tasks: ListOfTasks; })[] & ListOfProjects; } & AccountRoot & co<AccountRoot | null>
myProjects.
AccountRoot.myProjects: (Project & { tasks: ListOfTasks; })[] & ListOfProjects & co<ListOfProjects | null>
Array<T>.map<React.JSX.Element>(callbackfn: (value: Project & { tasks: ListOfTasks; }, index: number, array: (Project & { tasks: ListOfTasks; })[]) => React.JSX.Element, thisArg?: any): React.JSX.Element[] (+1 overload)
Calls a defined callback function on each element of an array, and returns an array that contains the results.map(project => ( <
project: Project & { tasks: ListOfTasks; }
JSX.IntrinsicElements.li: React.DetailedHTMLProps<React.LiHTMLAttributes<HTMLLIElement>, HTMLLIElement>
liReact.Attributes.key?: React.Key | null | undefined
key={project.
project: Project & { tasks: ListOfTasks; }
CoMap.id: ID<Project & { tasks: ListOfTasks; }>
The ID of this `CoMap`id}> {project.
project: Project & { tasks: ListOfTasks; }
Project.name: co<string>
name} ({project.
project: Project & { tasks: ListOfTasks; }
Project.tasks: co<ListOfTasks | null> & ListOfTasks
tasks.Array<T>.length: number
Gets or sets the length of the array. This is a number one higher than the highest index in the array.length} tasks) </JSX.IntrinsicElements.li: React.DetailedHTMLProps<React.LiHTMLAttributes<HTMLLIElement>, HTMLLIElement>
li> ))} </JSX.IntrinsicElements.ul: React.DetailedHTMLProps<React.HTMLAttributes<HTMLUListElement>, HTMLUListElement>
ul> </JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div> }
Loading States and Permission Checking
When subscribing to or loading a CoValue, you need to handle three possible states:
undefined
: The initial loading state, indicating the value is being fetchednull
: The CoValue was not found or is not accessible (e.g., due to permissions)Value
: The successfully loaded CoValue instance
This allows you to handle loading, error, and success states in your application:
class Task
Task.CoMap.subscribe<Task, true>(this: CoValueClass<Task>, id: ID<Task>, listener: (value: Task, unsubscribe: () => void) => void): () => void (+1 overload)
Load and subscribe to a `CoMap` with a given ID, as a given account. Automatically also subscribes to updates to all referenced/nested CoValues as soon as they are accessed in the listener. `depth` specifies which (if any) fields that reference other CoValues to load as well before calling `listener` for the first time. The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth. You can pass `[]` or `{}` for shallowly loading only this CoMap, or `{ fieldA: depthA, fieldB: depthB }` for recursively loading referenced CoValues. Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest. Returns an unsubscribe function that you should call when you no longer need updates. Also see the `useCoState` hook to reactively subscribe to a CoValue in a React component.subscribe(const taskId: ID<Task>
taskId, (task: Task
task) => { if (task: Task
task ===var undefined
undefined) {var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without calling `require('console')`. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information.log("Task is loading..."); } else if (task: Task
task === null) {var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without calling `require('console')`. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information.log("Task not found or not accessible"); } else {var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without calling `require('console')`. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information.log("Task loaded:",task: Task
task.Task.title: co<string>
title); } });
Deep Loading
When working with related CoValues (like tasks in a project), you often need to load not just the top-level object but also its nested references. This is especially important when working with CoMaps that contain references to other CoValues or with CoLists that contain multiple items. Jazz provides a flexible mechanism for specifying exactly how much of the object graph to load.
Resolve queries
Resolve queries let you declare exactly which references to load and how deep to go using the resolve
property:
class
class Project
Project extendsclass CoMap
CoMaps are collaborative versions of plain objects, mapping string-like keys to values.CoMap {Project.name: co<string>
name =co.
const co: { string: co<string>; number: co<number>; boolean: co<boolean>; null: co<null>; Date: co<Date>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number]>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T>; encoded<T>(arg: Encoder<T>): co<T>; ref: { ...; }; items: ItemsSym; optional: { ref: <C extends CoValueClass>(arg: C | ((_raw: InstanceType<C>["_raw"]) => C)) => co<InstanceType<C> | null | undefined>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T | undefined>; encoded<T>(arg: OptionalEncoder<T>): co<T | undefined>; string: co<string | undefined>; number: co<number | undefined>; boolean: co<boolean | undefined>; null: co<null | undefined>; Date: co<Date | undefined>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number] | undefined>; }; }
string: co<string>
string;Project.tasks: co<ListOfTasks | null>
tasks =co.
const co: { string: co<string>; number: co<number>; boolean: co<boolean>; null: co<null>; Date: co<Date>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number]>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T>; encoded<T>(arg: Encoder<T>): co<T>; ref: { ...; }; items: ItemsSym; optional: { ref: <C extends CoValueClass>(arg: C | ((_raw: InstanceType<C>["_raw"]) => C)) => co<InstanceType<C> | null | undefined>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T | undefined>; encoded<T>(arg: OptionalEncoder<T>): co<T | undefined>; string: co<string | undefined>; number: co<number | undefined>; boolean: co<boolean | undefined>; null: co<null | undefined>; Date: co<Date | undefined>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number] | undefined>; }; }
ref: <typeof ListOfTasks>(arg: typeof ListOfTasks | ((_raw: RawCoList<JsonValue, JsonObject | null>) => typeof ListOfTasks), options?: never) => co<...> (+1 overload)
ref(class ListOfTasks
ListOfTasks);Project.owner: co<TeamMember | null>
owner =co.
const co: { string: co<string>; number: co<number>; boolean: co<boolean>; null: co<null>; Date: co<Date>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number]>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T>; encoded<T>(arg: Encoder<T>): co<T>; ref: { ...; }; items: ItemsSym; optional: { ref: <C extends CoValueClass>(arg: C | ((_raw: InstanceType<C>["_raw"]) => C)) => co<InstanceType<C> | null | undefined>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T | undefined>; encoded<T>(arg: OptionalEncoder<T>): co<T | undefined>; string: co<string | undefined>; number: co<number | undefined>; boolean: co<boolean | undefined>; null: co<null | undefined>; Date: co<Date | undefined>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number] | undefined>; }; }
ref(
ref: <typeof TeamMember>(arg: typeof TeamMember | ((_raw: RawCoMap<{ [key: string]: JsonValue | undefined; }, JsonObject | null>) => typeof TeamMember), options?: never) => co<...> (+1 overload)
class TeamMember
TeamMember); } classclass Task
Task extendsclass CoMap
CoMaps are collaborative versions of plain objects, mapping string-like keys to values.CoMap {Task.title: co<string>
title =co.
const co: { string: co<string>; number: co<number>; boolean: co<boolean>; null: co<null>; Date: co<Date>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number]>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T>; encoded<T>(arg: Encoder<T>): co<T>; ref: { ...; }; items: ItemsSym; optional: { ref: <C extends CoValueClass>(arg: C | ((_raw: InstanceType<C>["_raw"]) => C)) => co<InstanceType<C> | null | undefined>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T | undefined>; encoded<T>(arg: OptionalEncoder<T>): co<T | undefined>; string: co<string | undefined>; number: co<number | undefined>; boolean: co<boolean | undefined>; null: co<null | undefined>; Date: co<Date | undefined>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number] | undefined>; }; }
string: co<string>
string;Task.subtasks: co<ListOfTasks | null>
subtasks =co.
const co: { string: co<string>; number: co<number>; boolean: co<boolean>; null: co<null>; Date: co<Date>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number]>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T>; encoded<T>(arg: Encoder<T>): co<T>; ref: { ...; }; items: ItemsSym; optional: { ref: <C extends CoValueClass>(arg: C | ((_raw: InstanceType<C>["_raw"]) => C)) => co<InstanceType<C> | null | undefined>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T | undefined>; encoded<T>(arg: OptionalEncoder<T>): co<T | undefined>; string: co<string | undefined>; number: co<number | undefined>; boolean: co<boolean | undefined>; null: co<null | undefined>; Date: co<Date | undefined>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number] | undefined>; }; }
ref: <typeof ListOfTasks>(arg: typeof ListOfTasks | ((_raw: RawCoList<JsonValue, JsonObject | null>) => typeof ListOfTasks), options?: never) => co<...> (+1 overload)
ref(class ListOfTasks
ListOfTasks);Task.assignee: co<TeamMember | null | undefined>
assignee =co.
const co: { string: co<string>; number: co<number>; boolean: co<boolean>; null: co<null>; Date: co<Date>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number]>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T>; encoded<T>(arg: Encoder<T>): co<T>; ref: { ...; }; items: ItemsSym; optional: { ref: <C extends CoValueClass>(arg: C | ((_raw: InstanceType<C>["_raw"]) => C)) => co<InstanceType<C> | null | undefined>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T | undefined>; encoded<T>(arg: OptionalEncoder<T>): co<T | undefined>; string: co<string | undefined>; number: co<number | undefined>; boolean: co<boolean | undefined>; null: co<null | undefined>; Date: co<Date | undefined>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number] | undefined>; }; }
optional.
optional: { ref: <C extends CoValueClass>(arg: C | ((_raw: InstanceType<C>["_raw"]) => C)) => co<InstanceType<C> | null | undefined>; ... 7 more ...; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number] | undefined>; }
ref(
ref: <typeof TeamMember>(arg: typeof TeamMember | ((_raw: RawCoMap<{ [key: string]: JsonValue | undefined; }, JsonObject | null>) => typeof TeamMember)) => co<...>
class TeamMember
TeamMember); } classclass TeamMember
TeamMember extendsclass CoMap
CoMaps are collaborative versions of plain objects, mapping string-like keys to values.CoMap {TeamMember.name: co<string>
name =co.
const co: { string: co<string>; number: co<number>; boolean: co<boolean>; null: co<null>; Date: co<Date>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number]>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T>; encoded<T>(arg: Encoder<T>): co<T>; ref: { ...; }; items: ItemsSym; optional: { ref: <C extends CoValueClass>(arg: C | ((_raw: InstanceType<C>["_raw"]) => C)) => co<InstanceType<C> | null | undefined>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T | undefined>; encoded<T>(arg: OptionalEncoder<T>): co<T | undefined>; string: co<string | undefined>; number: co<number | undefined>; boolean: co<boolean | undefined>; null: co<null | undefined>; Date: co<Date | undefined>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number] | undefined>; }; }
string: co<string>
string; } classclass ListOfTasks
ListOfTasks extendsclass CoList<Item = any>
CoLists are collaborative versions of plain arrays.CoList.
CoList<Item = any>.Of<co<Task | null>>(item: co<Task | null>): { new (options: { fromRaw: RawCoList; } | undefined): CoList<co<Task | null>>; ... 12 more ...; fromAsync<T>(iterableOrArrayLike: AsyncIterable<T> | Iterable<T | PromiseLike<T>> | ArrayLike<T | PromiseLike<T>>): Promise<T[]>; fromAsync<T, U>(iterableOrArrayLike: AsyncIterable<T> | Iterable<T> | ArrayLike<T>, mapFn: (value: Awaited<T>, index: number) => U, thisArg?: any): Promise<Awaited<U>[]>; }
Declare a `CoList` by subclassing `CoList.Of(...)` and passing the item schema using `co`.Of(co.
const co: { string: co<string>; number: co<number>; boolean: co<boolean>; null: co<null>; Date: co<Date>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number]>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T>; encoded<T>(arg: Encoder<T>): co<T>; ref: { ...; }; items: ItemsSym; optional: { ref: <C extends CoValueClass>(arg: C | ((_raw: InstanceType<C>["_raw"]) => C)) => co<InstanceType<C> | null | undefined>; json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T | undefined>; encoded<T>(arg: OptionalEncoder<T>): co<T | undefined>; string: co<string | undefined>; number: co<number | undefined>; boolean: co<boolean | undefined>; null: co<null | undefined>; Date: co<Date | undefined>; literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number] | undefined>; }; }
ref(
ref: <typeof Task>(arg: typeof Task | ((_raw: RawCoMap<{ [key: string]: JsonValue | undefined; }, JsonObject | null>) => typeof Task), options?: never) => co<...> (+1 overload)
class Task
Task)) {} // Load just the project, not its references constconst project: Project | null
project = awaitclass Project
Project.
CoMap.load<Project, true>(this: CoValueClass<...>, id: ID<Project>, options?: { resolve?: RefsToResolve<Project, 10, []> | undefined; loadAs?: Account | AnonymousJazzAgent; } | undefined): Promise<...>
Load a `CoMap` with a given ID, as a given account. `depth` specifies which (if any) fields that reference other CoValues to load as well before resolving. The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth. You can pass `[]` or `{}` for shallowly loading only this CoMap, or `{ fieldA: depthA, fieldB: depthB }` for recursively loading referenced CoValues. Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.load(const projectId: ID<Project>
projectId); if (!const project: Project | null
project) { throw newError("Project not found or not accessible"); } // string - primitive fields are always loaded
var Error: ErrorConstructor new (message?: string, options?: ErrorOptions) => Error (+1 overload)
const project: Project
project.Project.name: co<string>
name; // undefined | null | ListOfTasks - non-requested references might not be loaded, or inaccessibleconst project: Project
project.Project.tasks: co<ListOfTasks | null>
tasks; // Load the project and shallowly load its list of tasks constprojectWithTasksShallow = await
const projectWithTasksShallow: ({ tasks: ListOfTasks; } & Project) | null
class Project
Project.
CoMap.load<Project, { tasks: boolean; }>(this: CoValueClass<...>, id: ID<Project>, options?: { resolve?: RefsToResolve<Project, 10, []> | undefined; loadAs?: Account | AnonymousJazzAgent; } | undefined): Promise<...>
Load a `CoMap` with a given ID, as a given account. `depth` specifies which (if any) fields that reference other CoValues to load as well before resolving. The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth. You can pass `[]` or `{}` for shallowly loading only this CoMap, or `{ fieldA: depthA, fieldB: depthB }` for recursively loading referenced CoValues. Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.load(const projectId: ID<Project>
projectId, {resolve?: RefsToResolve<Project, 10, []> | undefined
resolve: {tasks?: RefsToResolve<ListOfTasks, 10, [0]> | undefined
tasks: true } }); if (!projectWithTasksShallow) { throw new
const projectWithTasksShallow: ({ tasks: ListOfTasks; } & Project) | null
Error("Project or required references not found or not accessible"); } // ListOfTasks - shallowly loaded
var Error: ErrorConstructor new (message?: string, options?: ErrorOptions) => Error (+1 overload)
projectWithTasksShallow.
const projectWithTasksShallow: { tasks: ListOfTasks; } & Project
Project.tasks: ListOfTasks & co<ListOfTasks | null>
tasks; // number - length of the listprojectWithTasksShallow.
const projectWithTasksShallow: { tasks: ListOfTasks; } & Project
Project.tasks: ListOfTasks & co<ListOfTasks | null>
tasks.Array<T>.length: number
Gets or sets the length of the array. This is a number one higher than the highest index in the array.length; // undefined | null | Task - items might not be loaded, or inaccessibleprojectWithTasksShallow.
const projectWithTasksShallow: { tasks: ListOfTasks; } & Project
Project.tasks: ListOfTasks & co<ListOfTasks | null>
tasks[0]; // Load the project and its tasks constprojectWithTasks = await
const projectWithTasks: ({ tasks: Task[] & ListOfTasks; } & Project) | null
class Project
Project.
CoMap.load<Project, { tasks: { $each: boolean; }; }>(this: CoValueClass<...>, id: ID<Project>, options?: { resolve?: RefsToResolve<Project, 10, []> | undefined; loadAs?: Account | AnonymousJazzAgent; } | undefined): Promise<...>
Load a `CoMap` with a given ID, as a given account. `depth` specifies which (if any) fields that reference other CoValues to load as well before resolving. The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth. You can pass `[]` or `{}` for shallowly loading only this CoMap, or `{ fieldA: depthA, fieldB: depthB }` for recursively loading referenced CoValues. Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.load(const projectId: ID<Project>
projectId, {resolve?: RefsToResolve<Project, 10, []> | undefined
resolve: {tasks?: RefsToResolve<ListOfTasks, 10, [0]> | undefined
tasks: {$each: RefsToResolve<Task, 10, [0, 0]>
$each: true } } }); if (!projectWithTasks) { throw new
const projectWithTasks: ({ tasks: Task[] & ListOfTasks; } & Project) | null
Error("Project or required references not found or not accessible"); } // ListOfTasks - fully loaded
var Error: ErrorConstructor new (message?: string, options?: ErrorOptions) => Error (+1 overload)
projectWithTasks.
const projectWithTasks: { tasks: Task[] & ListOfTasks; } & Project
Project.tasks: Task[] & ListOfTasks & co<ListOfTasks | null>
tasks; // Task - fully loadedprojectWithTasks.
const projectWithTasks: { tasks: Task[] & ListOfTasks; } & Project
Project.tasks: Task[] & ListOfTasks & co<ListOfTasks | null>
tasks[0]; // string - primitive fields are always loadedprojectWithTasks.
const projectWithTasks: { tasks: Task[] & ListOfTasks; } & Project
Project.tasks: Task[] & ListOfTasks & co<ListOfTasks | null>
tasks[0].Task.title: co<string>
title; // undefined | null | ListOfTasks - subtasks might not be loaded, or inaccessibleprojectWithTasks.
const projectWithTasks: { tasks: Task[] & ListOfTasks; } & Project
Project.tasks: Task[] & ListOfTasks & co<ListOfTasks | null>
tasks[0].Task.subtasks: co<ListOfTasks | null>
subtasks; // Load the project, its tasks, and their subtasks constprojectDeep = await
const projectDeep: ({ tasks: (Task & { subtasks: Task[] & ListOfTasks; assignee: TeamMember | undefined; })[] & ListOfTasks; } & Project) | null
class Project
Project.
CoMap.load<Project, { tasks: { $each: { subtasks: { $each: boolean; }; assignee: boolean; }; }; }>(this: CoValueClass<...>, id: ID<Project>, options?: { resolve?: RefsToResolve<Project, 10, []> | undefined; loadAs?: Account | AnonymousJazzAgent; } | undefined): Promise<...>
Load a `CoMap` with a given ID, as a given account. `depth` specifies which (if any) fields that reference other CoValues to load as well before resolving. The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth. You can pass `[]` or `{}` for shallowly loading only this CoMap, or `{ fieldA: depthA, fieldB: depthB }` for recursively loading referenced CoValues. Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.load(const projectId: ID<Project>
projectId, {resolve?: RefsToResolve<Project, 10, []> | undefined
resolve: {tasks?: RefsToResolve<ListOfTasks, 10, [0]> | undefined
tasks: {$each: RefsToResolve<Task, 10, [0, 0]>
$each: {subtasks?: RefsToResolve<ListOfTasks, 10, [0, 0, 0]> | undefined
subtasks: {$each: RefsToResolve<Task, 10, [0, 0, 0, 0]>
$each: true },assignee?: RefsToResolve<TeamMember, 10, [0, 0, 0]> | undefined
assignee: true } } } }); if (!projectDeep) { throw new
const projectDeep: ({ tasks: (Task & { subtasks: Task[] & ListOfTasks; assignee: TeamMember | undefined; })[] & ListOfTasks; } & Project) | null
Error("Project or required references not found or not accessible"); } // string - primitive fields are always loaded
var Error: ErrorConstructor new (message?: string, options?: ErrorOptions) => Error (+1 overload)
projectDeep.
const projectDeep: { tasks: (Task & { subtasks: Task[] & ListOfTasks; assignee: TeamMember | undefined; })[] & ListOfTasks; } & Project
tasks[0].
Project.tasks: (Task & { subtasks: Task[] & ListOfTasks; assignee: TeamMember | undefined; })[] & ListOfTasks & co<ListOfTasks | null>
Task.subtasks: co<ListOfTasks | null> & Task[] & ListOfTasks
subtasks[0].Task.title: co<string>
title; // undefined | null | TeamMember - since assignee is optional: // TeamMember - set and definitely loaded // null - set but unavailable/inaccessible // undefined - not set, or loading (in case of subscription)projectDeep.
const projectDeep: { tasks: (Task & { subtasks: Task[] & ListOfTasks; assignee: TeamMember | undefined; })[] & ListOfTasks; } & Project
tasks[0].
Project.tasks: (Task & { subtasks: Task[] & ListOfTasks; assignee: TeamMember | undefined; })[] & ListOfTasks & co<ListOfTasks | null>
Task.assignee: TeamMember | (TeamMember & CoMarker) | undefined
assignee;
The resolve query defines which parts of the graph you want to load, making it intuitive to express complex loading patterns.
Loading states and permissions
When loading data with references, the load operation will fail if one of the references is unavailable or if the user doesn't have read access to it. Let's explore what happens in various scenarios:
Resolved References
When a user tries to load a reference they don't have access to:
// If assignee is not accessible to the user: const
task = await
const task: ({ assignee: TeamMember | undefined; } & Task) | null
class Task
Task.
CoMap.load<Task, { assignee: boolean; }>(this: CoValueClass<...>, id: ID<Task>, options?: { resolve?: RefsToResolve<Task, 10, []> | undefined; loadAs?: Account | AnonymousJazzAgent; } | undefined): Promise<...>
Load a `CoMap` with a given ID, as a given account. `depth` specifies which (if any) fields that reference other CoValues to load as well before resolving. The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth. You can pass `[]` or `{}` for shallowly loading only this CoMap, or `{ fieldA: depthA, fieldB: depthB }` for recursively loading referenced CoValues. Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.load(const taskId: ID<Task>
taskId, {resolve?: RefsToResolve<Task, 10, []> | undefined
resolve: {assignee?: RefsToResolve<TeamMember, 10, [0]> | undefined
assignee: true } });task // => null
const task: ({ assignee: TeamMember | undefined; } & Task) | null
The load operation will fail and return null
if any requested reference is inaccessible. This maintains data consistency by ensuring all requested references are available before returning the object.
The behavior is the same for optional and required references.
List References
When a list contains references to items the user can't access:
// If any item in the list is not accessible: const
project = await
const project: ({ tasks: Task[] & ListOfTasks; } & Project) | null
class Project
Project.
CoMap.load<Project, { tasks: { $each: boolean; }; }>(this: CoValueClass<...>, id: ID<Project>, options?: { resolve?: RefsToResolve<Project, 10, []> | undefined; loadAs?: Account | AnonymousJazzAgent; } | undefined): Promise<...>
Load a `CoMap` with a given ID, as a given account. `depth` specifies which (if any) fields that reference other CoValues to load as well before resolving. The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth. You can pass `[]` or `{}` for shallowly loading only this CoMap, or `{ fieldA: depthA, fieldB: depthB }` for recursively loading referenced CoValues. Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.load(const projectId: ID<Project>
projectId, {resolve?: RefsToResolve<Project, 10, []> | undefined
resolve: {tasks?: RefsToResolve<ListOfTasks, 10, [0]> | undefined
tasks: {$each: RefsToResolve<Task, 10, [0, 0]>
$each: true } } });project // => null
const project: ({ tasks: Task[] & ListOfTasks; } & Project) | null
If any item in a list is inaccessible to the user, the entire load operation will fail and return null
. This is because lists expect all their items to be accessible - a partially loaded list could lead to data inconsistencies.
Reading a non-resolved inaccessible reference
When trying to load an object with an inaccessible reference without directly resolving it:
const
const project: Project | null
project = awaitclass Project
Project.
CoMap.load<Project, true>(this: CoValueClass<...>, id: ID<Project>, options?: { resolve?: RefsToResolve<Project, 10, []> | undefined; loadAs?: Account | AnonymousJazzAgent; } | undefined): Promise<...>
Load a `CoMap` with a given ID, as a given account. `depth` specifies which (if any) fields that reference other CoValues to load as well before resolving. The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth. You can pass `[]` or `{}` for shallowly loading only this CoMap, or `{ fieldA: depthA, fieldB: depthB }` for recursively loading referenced CoValues. Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.load(const projectId: ID<Project>
projectId, {resolve?: RefsToResolve<Project, 10, []> | undefined
resolve: true });const project: Project | null
project // => Project // The user doesn't have access to the ownerconst project: Project | null
project?.Project.owner: co<TeamMember | null> | undefined
owner // => always null
The load operation will succeed and return the object, but the inaccessible reference will always be null
.
Type Safety with Resolved Type
Jazz provides the Resolved
type to help you define and enforce the structure of deeply loaded data in your application. This makes it easier to ensure that components receive the data they expect with proper TypeScript validation.
The Resolved
type is especially useful when passing data between components, as it guarantees that all necessary nested data has been loaded:
// Define a type that includes resolved nested data type
ProjectWithTasks =
type ProjectWithTasks = { tasks: Task[] & ListOfTasks; } & Project
Resolved<
type Resolved<T, R extends RefsToResolve<T> | undefined> = R extends boolean | undefined ? T : [T] extends [(infer Item)[]] ? UnCo<Exclude<Item, null>> extends CoValue ? R extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & UnCo<...> : [...] extends [...] ? UnCo<...> extends CoValue ? ItemDepth extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & UnCo<...> : [...] extends [...] ? UnCo<...> extends CoValue ? ItemDepth extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & UnCo<...> : [...] extends [...] ? UnCo<...> extends CoValue ? ItemDepth extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & UnCo<...> : [...] extends [...] ? UnCo<...> extends CoValue ? ItemDepth extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & UnCo<...> : [...] extends [...] ? UnCo<...> extends CoValue ? ItemDepth extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & UnCo<...> : [...] extends [...] ? UnCo<...> extends CoValue ? ItemDepth extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & UnCo<...> : [...] extends [...] ? UnCo<...> extends CoValue ? ItemDepth extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & UnCo<...> : [...] extends [...] ? UnCo<...> extends CoValue ? ItemDepth extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue ...
class Project
Project, {tasks: {
tasks: { $each: true; }
$each: true
$each: true } }>; // Component that expects a fully resolved project functionTaskList({
function TaskList({ project }: { project: ProjectWithTasks; }): React.JSX.Element
project }: {
project: { tasks: Task[] & ListOfTasks; } & Project
project:
project: { tasks: Task[] & ListOfTasks; } & Project
ProjectWithTasks }) { // TypeScript knows tasks are loaded, so this is type-safe return ( <
type ProjectWithTasks = { tasks: Task[] & ListOfTasks; } & Project
JSX.IntrinsicElements.ul: React.DetailedHTMLProps<React.HTMLAttributes<HTMLUListElement>, HTMLUListElement>
ul> {project.
project: { tasks: Task[] & ListOfTasks; } & Project
Project.tasks: Task[] & ListOfTasks & co<ListOfTasks | null>
tasks.Array<T>.map<React.JSX.Element>(callbackfn: (value: Task, index: number, array: Task[]) => React.JSX.Element, thisArg?: any): React.JSX.Element[] (+1 overload)
Calls a defined callback function on each element of an array, and returns an array that contains the results.map(task: Task
task => ( <JSX.IntrinsicElements.li: React.DetailedHTMLProps<React.LiHTMLAttributes<HTMLLIElement>, HTMLLIElement>
liReact.Attributes.key?: React.Key | null | undefined
key={task: Task
task.CoMap.id: ID<Task>
The ID of this `CoMap`id}>{task: Task
task.Task.title: co<string>
title}</JSX.IntrinsicElements.li: React.DetailedHTMLProps<React.LiHTMLAttributes<HTMLLIElement>, HTMLLIElement>
li> ))} </JSX.IntrinsicElements.ul: React.DetailedHTMLProps<React.HTMLAttributes<HTMLUListElement>, HTMLUListElement>
ul> ); } // For more complex resolutions typeFullyLoadedProject =
type FullyLoadedProject = { tasks: (Task & { subtasks: ListOfTasks; assignee: TeamMember | undefined; })[] & ListOfTasks; owner: TeamMember; } & Project
Resolved<
type Resolved<T, R extends RefsToResolve<T> | undefined> = R extends boolean | undefined ? T : [T] extends [(infer Item)[]] ? UnCo<Exclude<Item, null>> extends CoValue ? R extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & UnCo<...> : [...] extends [...] ? UnCo<...> extends CoValue ? ItemDepth extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & UnCo<...> : [...] extends [...] ? UnCo<...> extends CoValue ? ItemDepth extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & UnCo<...> : [...] extends [...] ? UnCo<...> extends CoValue ? ItemDepth extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & UnCo<...> : [...] extends [...] ? UnCo<...> extends CoValue ? ItemDepth extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & UnCo<...> : [...] extends [...] ? UnCo<...> extends CoValue ? ItemDepth extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & UnCo<...> : [...] extends [...] ? UnCo<...> extends CoValue ? ItemDepth extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & UnCo<...> : [...] extends [...] ? UnCo<...> extends CoValue ? ItemDepth extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & UnCo<...> : [...] extends [...] ? UnCo<...> extends CoValue ? ItemDepth extends { ...; } ? (CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue ...
class Project
Project, {tasks: {
tasks: { $each: { subtasks: true; assignee: true; }; }
$each: {
$each: { subtasks: true; assignee: true; }
subtasks: true
subtasks: true,assignee: true
assignee: true } },owner: true
owner: true }>; // Function that requires deeply resolved data functionfunction processProject(project: FullyLoadedProject): void
processProject(project:
project: { tasks: (Task & { subtasks: ListOfTasks; assignee: TeamMember | undefined; })[] & ListOfTasks; owner: TeamMember; } & Project
FullyLoadedProject) { // Safe access to all resolved properties
type FullyLoadedProject = { tasks: (Task & { subtasks: ListOfTasks; assignee: TeamMember | undefined; })[] & ListOfTasks; owner: TeamMember; } & Project
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without calling `require('console')`. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information.log(`Project ${project.
project: { tasks: (Task & { subtasks: ListOfTasks; assignee: TeamMember | undefined; })[] & ListOfTasks; owner: TeamMember; } & Project
Project.name: co<string>
name} owned by ${project.
project: { tasks: (Task & { subtasks: ListOfTasks; assignee: TeamMember | undefined; })[] & ListOfTasks; owner: TeamMember; } & Project
Project.owner: TeamMember & co<TeamMember | null>
owner.TeamMember.name: co<string>
name}`);project.
project: { tasks: (Task & { subtasks: ListOfTasks; assignee: TeamMember | undefined; })[] & ListOfTasks; owner: TeamMember; } & Project
tasks.
Project.tasks: (Task & { subtasks: ListOfTasks; assignee: TeamMember | undefined; })[] & ListOfTasks & co<ListOfTasks | null>
Array<T>.forEach(callbackfn: (value: Task & { subtasks: ListOfTasks; assignee: TeamMember | undefined; }, index: number, array: (Task & { subtasks: ListOfTasks; assignee: TeamMember | undefined; })[]) => void, thisArg?: any): void (+1 overload)
Performs the specified action for each element in an array.forEach(task => {
task: Task & { subtasks: ListOfTasks; assignee: TeamMember | undefined; }
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without calling `require('console')`. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information.log(`Task: ${task.
task: Task & { subtasks: ListOfTasks; assignee: TeamMember | undefined; }
Task.title: co<string>
title}, Assigned to: ${task.
task: Task & { subtasks: ListOfTasks; assignee: TeamMember | undefined; }
Task.assignee: TeamMember | (TeamMember & CoMarker) | undefined
assignee?.TeamMember.name: co<string> | undefined
name}`);var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without calling `require('console')`. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information.log(`Subtasks: ${task.
task: Task & { subtasks: ListOfTasks; assignee: TeamMember | undefined; }
Task.subtasks: co<ListOfTasks | null> & ListOfTasks
subtasks.Array<T>.length: number
Gets or sets the length of the array. This is a number one higher than the highest index in the array.length}`); }); }
Using the Resolved
type helps catch errors at compile time rather than runtime, ensuring that your components and functions receive data with the proper resolution depth. This is especially useful for larger applications where data is passed between many components.
Ensuring Data is Loaded
Sometimes you need to make sure data is loaded before proceeding with an operation. The ensureLoaded
method lets you guarantee that a CoValue and its referenced data are loaded to a specific depth:
async function
function completeAllTasks(projectId: ID<Project>): Promise<void>
completeAllTasks(projectId: ID<Project>
projectId:type ID<T> = `co_z${string}` & IDMarker<T>
IDs are unique identifiers for `CoValue`s. Can be used with a type argument to refer to a specific `CoValue` type.ID<class Project
Project>) { // Ensure the project is loaded constconst project: Project | null
project = awaitclass Project
Project.
CoMap.load<Project, true>(this: CoValueClass<...>, id: ID<Project>, options?: { resolve?: RefsToResolve<Project, 10, []> | undefined; loadAs?: Account | AnonymousJazzAgent; } | undefined): Promise<...>
Load a `CoMap` with a given ID, as a given account. `depth` specifies which (if any) fields that reference other CoValues to load as well before resolving. The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth. You can pass `[]` or `{}` for shallowly loading only this CoMap, or `{ fieldA: depthA, fieldB: depthB }` for recursively loading referenced CoValues. Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.load(projectId: ID<Project>
projectId, {resolve?: RefsToResolve<Project, 10, []> | undefined
resolve: true }); if (!const project: Project | null
project) return; // Ensure tasks are loaded constloadedProject = await
const loadedProject: { tasks: Task[] & ListOfTasks; } & Project
const project: Project
project.
CoMap.ensureLoaded<Project, { tasks: { $each: boolean; }; }>(this: Project, options: { resolve: RefsToResolve<Project, 10, []>; }): Promise<{ tasks: Task[] & ListOfTasks; } & Project>
Given an already loaded `CoMap`, ensure that the specified fields are loaded to the specified depth. Works like `CoMap.load()`, but you don't need to pass the ID or the account to load as again.ensureLoaded({resolve: RefsToResolve<Project, 10, []>
resolve: {tasks?: RefsToResolve<ListOfTasks, 10, [0]> | undefined
tasks: {$each: RefsToResolve<Task, 10, [0, 0]>
$each: true } } }); // Now we can safely access and modify tasksloadedProject.
const loadedProject: { tasks: Task[] & ListOfTasks; } & Project
Project.tasks: Task[] & ListOfTasks & co<ListOfTasks | null>
tasks.Array<T>.forEach(callbackfn: (value: Task, index: number, array: Task[]) => void, thisArg?: any): void (+1 overload)
Performs the specified action for each element in an array.forEach(task: Task
task => {task: Task
task.Task.status: co<"todo" | "in-progress" | "completed">
status = "completed"; }); }
Best Practices
- Be explicit about resolution depths: Always specify exactly what you need
- Use framework integrations: They handle subscription lifecycle automatically
- Clean up subscriptions: Always store and call the unsubscribe function when you're done
- Handle all loading states: Check for undefined (loading), null (not found), and success states
- Use the Resolved type: Add compile-time type safety for components that require specific resolution patterns