Giter Site home page Giter Site logo

kamiloox / use-socket-io-react Goto Github PK

View Code? Open in Web Editor NEW
4.0 1.0 1.0 146 KB

React.js wrapper for socket.io-client

Home Page: https://www.npmjs.com/package/use-socket-io-react

License: MIT License

Shell 1.01% JavaScript 2.74% TypeScript 96.25%
reactjs socket-io typescript websocket

use-socket-io-react's Introduction

Written with ❤️ It's 100% typesafe to make React.js developer experience better with socket.io-client.

Socket.io TypeScript React.js

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.

Module augmentation

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.

In the a root of a project (e.g. in the src) create a file 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,
});

Disclaimer. If this feature doesn't work try adding a path to a typeRoots in a tsconfig.json.

{
  "compilerOptions": {
    "typeRoots": ["./src/types"]
  },
}

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!

use-socket-io-react's People

Contributors

kamiloox avatar

Stargazers

Sodabeh avatar mduvernon avatar barakcodes avatar  avatar

Watchers

 avatar

Forkers

lodu

use-socket-io-react's Issues

feat(useSocketEvent): provide option for schema validation

Currently fields that are returned by useSocketEvent are not validated. It would be great to have an opportunity to pass a schema as an optional argument.
It needs to be done as much schema validation library agnostic as possible. Do not implement it to support only specific validation libraries like e.g. zod, yod or joi. Check if it's possible to validate it asynchronously to either resolve it successfully or throw an error.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.