Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/desmondhiew00/socket.io-client-react-hook
https://github.com/desmondhiew00/socket.io-client-react-hook
Last synced: 3 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/desmondhiew00/socket.io-client-react-hook
- Owner: desmondhiew00
- License: mit
- Created: 2022-03-01T15:11:55.000Z (almost 3 years ago)
- Default Branch: master
- Last Pushed: 2022-03-01T15:47:42.000Z (almost 3 years ago)
- Last Synced: 2024-04-24T10:48:36.175Z (9 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[![npm](https://img.shields.io/npm/v/socket.io-client-react-hook.svg?style=flat-square)](https://www.npmjs.com/package/socket.io-client-react-hook)
[![npm](https://img.shields.io/npm/dt/socket.io-client-react-hook?style=flat-square)](https://www.npmtrends.com/socket.io-client-react-hook)
[![npm bundle size](https://img.shields.io/bundlephobia/minzip/socket.io-client-react-hook?style=flat-square)](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;
```