Skip to content

Documentation / @super-line/react / createSuperLineHooks

Function: createSuperLineHooks()

createSuperLineHooks<C, R>(): object

Defined in: index.ts:47

Bind typed React hooks to a contract + role. Create the client once, wrap your tree in the returned <Provider>, then use the hooks inside.

Type Parameters

C

C extends Contract

R

R extends string

Returns

Provider

Provider: (props) => ReactNode

Provides a connected client to the hooks below.

Parameters

props
children?

ReactNode

client

SuperLineClient<C, R>

Returns

ReactNode

useClient

useClient: () => SuperLineClient<C, R>

Access the client from context (throws outside a <Provider>).

Returns

SuperLineClient<C, R>

useEvent

useEvent: <E>(event, handler) => void

Subscribe to a server-pushed event for the component's lifetime.

Type Parameters

E

E extends string | number | symbol

Parameters

event

E

handler

(data) => void

Returns

void

useRequest

useRequest: <M>(method) => RequestState<Output<Requests<C, R>[M]>> & object

Wrap a request as { data, error, isLoading, call } for use in components.

Type Parameters

M

M extends string | number | symbol

Parameters

method

M

Returns

RequestState<Output<Requests<C, R>[M]>> & object

useResource

useResource: <T>(name, id) => object

Open a Store Resource and track it reactively: returns its latest data (undefined until the catch-up snapshot arrives) plus set/update to write through. data is untyped — stores are off-contract (ADR-0003) — so pass T to assert its shape. The handle is closed on unmount.

Type Parameters

T

T = unknown

Parameters

name

string

id

string

Returns

object

data

data: T | undefined

set

set: (value) => void

Parameters
value

T

Returns

void

update

update: (partial) => void

Parameters
partial

Partial<T>

Returns

void

useSubscription

useSubscription: <T>(topic) => EventData<TopicsOf<ServerMessages<C, R>>[T]> | undefined

Subscribe to a topic and return its latest value (or undefined before the first message).

Type Parameters

T

T extends string | number | symbol

Parameters

topic

T

Returns

EventData<TopicsOf<ServerMessages<C, R>>[T]> | undefined

Example

tsx
const { Provider, useRequest, useEvent, useSubscription } = createSuperLineHooks<typeof api, 'user'>()

function Root() {
  const [client] = useState(() => createSuperLineClient(api, { url, role: 'user' }))
  return <Provider client={client}><Room /></Provider>
}

Released under the MIT License.