Skip to content

Documentation / @super-line/react / createSocketReact

Function: createSocketReact()

createSocketReact<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

Client<C, R>

Returns

ReactNode

useClient

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

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

Returns

Client<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

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 } = createSocketReact<typeof api, 'user'>()

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

Released under the MIT License.