https://github.com/desmondhiew00/socket.io-client-react-hook
https://github.com/desmondhiew00/socket.io-client-react-hook
Last synced: 6 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/desmondhiew00/socket.io-client-react-hook
- Owner: desmondhiew00
- License: mit
- Archived: true
- Created: 2022-03-01T15:11:55.000Z (over 3 years ago)
- Default Branch: master
- Last Pushed: 2022-03-01T15:47:42.000Z (over 3 years ago)
- Last Synced: 2025-04-20T06:03:42.859Z (6 months ago)
- Language: TypeScript
- Size: 15.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
#### socket.io client for @nestjs/platform-socket.io v7 with react hooks
##### socket.io-client v2.3.0[](https://www.npmjs.com/package/socket.io-client-react-hook)
[](https://www.npmtrends.com/socket.io-client-react-hook)
[](https://bundlephobia.com/result?p=socket.io-client-react-hook)## Installation
```sh
yarn add socket.io-client-react-hook
```## Usage
```tsx
import { useEffect, useState, useRef } from 'react';
import useSocketClient from 'socket.io-client-react-hook';const wsUrl = 'ws://localhost:3000';
const Index: React.FC = () => {
const room = `chat-room-001`;
const chatsRef = useRef([]);
const [chats, setChats] = useState([]);
const { client, connected } = useSocketClient(wsUrl, {
transports: ['websocket'],
});useEffect(() => {
if (connected && client) client.emit('join-room', room);
return () => {
if (client) client.emit('leave-room', room);
};
}, [connected, client]);useEffect(() => {
if (!client) return;
client.on('event:message_received', (val: any) => {
onChatReceived(val || 'new message');
});
}, [client]);useEffect(() => {
chatsRef.current = chats;
}, [chats]);const onChatReceived = (val: string) => {
const ary = Array.from(chatsRef.current);
ary.push(val);
setChats(ary);
};return (
React Socket.IO Client Hook
Connection Status:
{connected ? 'Connected' : 'Disconnected'}
Messages
{chats.map((msg, index) => (
{index + 1}: {msg}
))}
);
};export default Index;
```