0.0.10 • Published 1 year ago

qwik-ws v0.0.10

Weekly downloads
-
License
-
Repository
github
Last release
1 year ago

Qwik Ws

A simple hook for using a websocket on the client.

Install

Add Qwik Ws to your project with one of the following commands

NPM

npm install qwik-ws

Yarn

yarn add qwik-ws

PNPM

pnpm add qwik-ws

Usage

Import

import { useWs } from "qwik-ws";

Example

import { $, component$ } from "@builder.io/qwik";
// Optional, you can just use import instead of import type.
import type {
	CloseEventFunction,
	ErrorEventFunction,
	MessageEventFunction,
	OpenEventFunction,
} from "qwik-ws";
import { useWs } from "qwik-ws";

export default component$(() => {
	const onOpen$: OpenEventFunction = $((ev, ws) => {
		console.log("WebSocket Opened", ev.timeStamp);
		ws.send("Hello World!");
	});

	const onError$: ErrorEventFunction = $((ev, ws) => {
		console.log("Received error");

		ws.close();
	});

	const onMessage$: MessageEventFunction = $((ev, ws) => {
		console.log("Received Message", ev.data);

		ws.close();
	});

	const onClose$: CloseEventFunction = $((ev, ws, funcs) => {
		console.log("Websocket Closed", ev.timeStamp);
		console.log(ws.readyState);

		// Events can access the additional websocket functions provided in the 3rd argument.
		funcs.reconnect();
	});

	const websocket = useWs("ws://localhost:8080", {
		protocols: ["JSON"],
		onOpen$,
		onError$,
		onMessage$,
		onClose$,
	});

	return (
		<div>
			<button
				onClick$={() => {
					websocket?.ws?.send("Hello World!");
				}}
			>
				Send Message
			</button>
			<button
				onClick$={() => {
					websocket?.ws?.close();
				}}
			>
				Close Websocket
			</button>
			{/* This will manually reconnect to the url
			and protocols provided in the useWs hook. */}
			<button
				onClick$={() => {
					websocket?.reconnect();
				}}
			>
				Reconnect
			</button>
		</div>
	);
});
0.0.10

1 year ago

0.0.9

1 year ago

0.0.8

1 year ago

0.0.7

1 year ago

0.0.6

1 year ago

0.0.5

1 year ago

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago