A lightweight Pusher-like client using Socket.IO
npm install @showkat.dev/pusher-clientbash
npm install @showkat.dev/pusher-client
`
---
Usage
$3
`ts
import Pusher from "@showkat.dev/pusher-client";
// Initialize client with token
const pusher = new Pusher("YOUR_TOKEN", {
base_url: "http://localhost:8000",
});
// Subscribe to a channel
const chat = pusher.subscribe("chat");
// Listen for events
chat.bind("new-message", (data) => {
console.log("New message:", data);
});
// Listen to global events
pusher.bindGlobal((event, data) => {
console.log([GLOBAL] ${event}, data);
});
// Unsubscribe and disconnect
// chat.unbind("new-message");
// pusher.unsubscribe("chat");
// pusher.disconnect();
`
---
$3
`tsx
import React, { useEffect, useState } from "react";
import Pusher from "@showkat.dev/pusher-client";
const ChatRoom = ({ token }: { token: string }) => {
const [messages, setMessages] = useState([]);
useEffect(() => {
const pusher = new Pusher(token, { base_url: "http://localhost:8000" });
const chat = pusher.subscribe("chat");
chat.bind("new-message", (msg) => {
setMessages((prev) => [...prev, msg]);
});
return () => {
chat.unbind("new-message");
pusher.unsubscribe("chat");
pusher.disconnect();
};
}, [token]);
return (
{" "}
{messages.map((m, i) => (
{m.message}
))}
{" "}
);
};
`
---
API
$3
- token: token for authentication
- options.base_url: Socket.IO server URL (default: https://push.innomessage.com)
---
$3
#### subscribe(channelName: string)
- Subscribe to a channel
- Returns a Channel object
#### unsubscribe(channelName: string)
- Unsubscribe from a channel
#### bindGlobal(callback: (event: string, data: any) => void)
- Listen to all global events
#### unbindGlobal(callback?)
- Remove global event listener(s)
#### disconnect()
- Disconnects the client and clears all subscriptions
---
$3
#### bind(event: string, callback: (data: any) => void)
- Bind to a specific event on this channel
#### unbind(event: string, callback?)
- Remove listener(s) for this event
---
License
MIT © Showkat Ali
`
``