Path hooks resolve a JSON Pointer style path against a parent node and subscribe to changes underneath that parent. They are the fastest way to wire a deep field of a CRDT document to a React component. Every path hook accepts: - `path` --- a JSON CRDT [`ApiPath`][api-path] (a string like `/user/email` or an array of segments). - `node` --- the parent node to resolve against. Defaults to the node in [context][context-page]. - `event` --- the change event scope. Defaults to `'subtree'`. If the path cannot be resolved (or, for typed variants, the resolved node is of the wrong type), the hook returns `undefined` instead of throwing. [api-path]: /libs/json-joy-js/json-crdt [context-page]: /libs/collaborative-react/context ## `usePath(path, node?, event?)` Resolves a nested node by path and subscribes to changes on the parent. ```ts const usePath: ( path: ApiPath, node?: N, event?: 'self' | 'child' | 'subtree', ) => CrdtNodeApi | undefined; ``` ```ts import {usePath} from '@jsonjoy.com/collaborative-react'; const Field: React.FC<{path: string}> = ({path}) => { const node = usePath(path); if (!node) return null; return
{JSON.stringify(node.view())}
; }; ``` Returns the underlying `NodeApi` so you can call any of its methods---typed or not. For most cases the typed variants below are more convenient. ## `usePathView(path, node?, event?)` Same as `usePath()` but returns the resolved node's *view* directly. ```ts const usePathView: (path: ApiPath, node?, event?) => unknown; ``` ```ts const Email: React.FC = () => { const email = usePathView('/user/email') as string | undefined; return {email ?? '(none)'}; }; ``` ## Typed accessors When you know the type of node at the path, the typed accessors save a cast and a runtime check. ### `useStr(path?, node?, event?)` ```ts const useStr: (path?: ApiPath, node?, event?) => StrApi | undefined; ``` ```ts import {useStr} from '@jsonjoy.com/collaborative-react'; const TitleInput: React.FC = () => { const title = useStr('/title'); if (!title) return null; return ( { title.del(0, title.view().length); title.ins(0, e.target.value); }} /> ); }; ``` Returns a `StrApi` you can mutate with `.ins()`, `.del()`, and friends. Returns `undefined` if the path doesn't exist or the node is not a `str`. ~~~jj.note For real `` / `