socket.io-client-react-hook
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

socket.io client for @nestjs/platform-socket.io v7 with react hooks

socket.io-client v2.3.0

npm npm npm bundle size

Installation

yarn add socket.io-client-react-hook

Usage

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 (
    <div>
      <h1>React Socket.IO Client Hook</h1>

      <div>
        <span>
          Connection Status:
          <span style={{ margin: '0 20px', color: connected ? 'green' : 'gray' }}>
            {connected ? 'Connected' : 'Disconnected'}
          </span>
        </span>
      </div>
      <h4>Messages</h4>
      <div style={{ border: '1px solid black', width: 500, minHeight: 300 }}>
        {chats.map((msg, index) => (
          <div key={index}>
            {index + 1}: {msg}
          </div>
        ))}
      </div>
    </div>
  );
};

export default Index;

Package Sidebar

Install

npm i socket.io-client-react-hook

Weekly Downloads

2

Version

1.0.0

License

MIT

Unpacked Size

32.4 kB

Total Files

8

Last publish

Collaborators

  • desmondhiew