@liinkiing/use-socket
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

use-socket

A hook to use with socket.io.

Installation

With yarn

$ yarn add @liinkiing/use-socket

With npm

$ npm i @liinkiing/use-socket

Documentation

https://liinkiing.github.io/use-socket/globals.html

Example

import React, { FunctionComponent, useState } from 'react'
import { SocketProvider, useSocketOn, useSocket, useSocketEmit } from '@liinkiing/use-socket';

const Chat: FunctionComponent = () => {
  const [messages, setMessages] = useState([]);

  const socket = useSocket() // if you want to get access to your socket object

  // useSocketEmit("chat:send", { id: 'random', body: 'blabla'})
  // you can use this only if you are in the root body of your functional component
  // generally, you would use `socket = useSocket()` and then `socket.emit`, but maybe
  // this hook can serve ¯\_(ツ)_/¯

  useSocketOn("chat:message", newMessage =>
    setMessages([newMessage, ...messages])
  );

  return messages.length ? (
    <ul>
      {messages.map(message => (
        <li key={message.id}>{message.body}</li>
      ))}
    </ul>
  ) : (
    <p>No messages...</p>
  );
};

const App: FunctionComponent = () => (
  <SocketProvider url="https://your-ws-endpoint-here/">
    <Chat />
  </SocketProvider>
);

Package Sidebar

Install

npm i @liinkiing/use-socket

Weekly Downloads

8

Version

1.0.3

License

MIT

Unpacked Size

80.2 kB

Total Files

11

Last publish

Collaborators

  • linkingliplayer