npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-socket-io-react

v0.2.1

Published

React.js wrapper for socket.io-client

Downloads

15

Readme

Key features

  • Module augmentation to reuse your types that are on a backend. More on that here
  • TypeScript support
  • Reusable React.js hooks

Installation

  • With yarn

    yarn add use-socket-io-react
  • With npm

    npm install use-socket-io-react

Setup

Wrap the application with a SocketProvider. For example, with React 18 it can be done like so:

const SERVER_URI = 'http://localhost:4000';

ReactDOM.render(
  <SocketProvider uri={SERVER_UR}>
    <App />
  </SocketProvider>,
  document.getElementById('root'),
);

The URI prop needs to point to a backend server. Don't forget about handling a CORS policy on a server because since version 3 of a socket.io it needs to be set explicitly.

Handling events

There is a hook called useSocketEvent. As a first argument, it takes an event name and in a resolution, it returns an object with a data array. Values in an array match to an order in which values are passed to an io.emit on a server.

// Server
io.emit('alert', 'Hey, you are the best!');
// Client
const {
  data: [alert],
} = useSocketEvent<[string]>('alert');

if (alert) {
  return <p>You received an alert: ${alert}</p>;
}

Alternatively useSocketEvent provides a handler callback that gets dispatched when the socket receives an event.

// Server
io.emit('chat', 'Hello John!', '12:38');
// Client
const [messages, setMessages] = useState<
  Array<{ message: string; sentAt: string }>
>([]);

const handleMessage = ([message, sentAt]: [string, string]) => {
  setMessages([...messages, { message: message, sentAt: sentAt }]);
};

useSocketEvent<[string, string]>('chat', {
  handler: handleMessage,
});

return (
  <section>
    {messages.map(({ message, sentAt }) => (
      <p>
        {message} ({sentAt})
      </p>
    ))}
  </section>
);

Emitting events

For emitting there is a hook called useSocketEmit. It doesn't take any argument but it returns an emit function.

const { emit } = useSocketEmit();

emit<[string]>('message', ['Hey, this is my message']);

You can provide a generic of how your emitted values need to look, but that's not recommended. Take a look at module augmentation

Socket state

Hook called useSocket stores values about a current socket state. It knows e.g. if a socket is either connected or there is some error.

const {
  socket,
  status,
  isConnected,
  isConnecting,
  isDisconnected,
  disconnectReason,
  isError,
  error,
} = useSocket();

// Or you can check: status === 'error'
if (isError) {
  return <p>Error! {error}</p>;
}

if (isDisconnected) {
  return <p>Socket disconnected {disconnectReason}</p>;
}

if (isConnecting) {
  return <p>Is loading</p>;
}

In addition, useSocket returns a native socket from a socket.io-client if some feature is needed that's currently beyond this library.

Socket.io introduces TypeScript support. This library supports this idea too. It's possible to abandon passing generic to every useSocketEvent and useSocketEmit hook thankfully to a module augmentation feature.

Create a file in your project called types/use-socket-io-react.d.ts and paste this.

import 'use-socket-io-react';

declare module 'use-socket-io-react' {
  interface ServerToClientEvents {
    chat: (message: string, sentAt: number) => void;
  }

  interface ClientToServerEvents {
    alert: (content: string) => void;
  }
}

These interfaces are copied directly from a backend. There is no need to worry about the specific conventions for this package. If on a backend server a TypeScript is used then it's easy to extend it.

const { emit } = useSocketEmit();

// Argument of type '[]' is not assignable to parameter of type '[content: string]'.
// Source has 0 element(s) but target requires 1.
emit('alert', []);
const handleMessage: EventHandler<'chat'> = ([message]) => {
  console.log(`There is a message ${message}`);
};

useSocketEvent('chat', {
  handler: handleMessage,
});

Additional notes

  • Package uses the 4th major version of a socket.io-client.
  • This project uses conventional commits convention
  • This is still in development. But there are more incoming updates in the future!