Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

📄 Add examples to README #23

Merged
merged 1 commit into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions websocket/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,49 @@ API as an Effection resource. Instead of a fragile, spring-loaded confederation
of 'open', 'close', 'error', and 'message' event handlers, `useWebSocket()`
organizes them for you so that you can consume all events from the server as a
plain stream that has state-readiness and proper error handling baked in.

To use a websocket import the `useWebSocket()` operation which behaves just like
the [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)
constructor.

```ts
import { main, each } from "effection";
import { useWebSocket } from "
cowboyd marked this conversation as resolved.
Show resolved Hide resolved


await main(function*() {
let socket = yield* useWebSocket("ws://websocket.example.org");

socket.send("Hello World");

for (let message of yield* each(socket)) {
console.log('Message from server', message);
yield* each.next();
}
});
```

The resource provides the following niceties:

- When `useWebSocket()` returns, it will have already received the `open` event.
- If the socket recieves an error event, that event's error will be thrown to
the current error boundary.
- The socket is a stream whose items are each `MessageEvents`, the `CloseEvent`
of the websocket will be the close event of that stream.

You can also instantiate a websocket separately and pass it along to
`useWebSocket()`. This is helpful for runtimes such as NodeJS prior to version
21 that do not have built in support for websocket.

```
cowboyd marked this conversation as resolved.
Show resolved Hide resolved
import { createWebSocket } from "my-websocket-client";

await main(function*() {
let socket = yield* useWebSocket(() => createWebSocket("ws://websocket.example.org"));

for (let message of yield* each(socket)) {
console.log('Message from server', message);
yield* each.next();
}
});
```
3 changes: 3 additions & 0 deletions websocket/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,7 @@ export function useWebSocket<T>(
});
}

/**
* @ignore
*/
export type WebSocketData = Parameters<WebSocket["send"]>[0];
Loading