0.3.0 • Published 1 month ago

use-transport v0.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 month ago

use-transport

Node CI npm license

A React hook with simple and responsible universal transports.

Motivation

use-transport is a React hook that provides a simple and responsible way to manage data transport. It is designed to be used with data-transport to provide a universal transport solution.

data-transport is a generic and responsible communication transporter:

  • iframe
  • Broadcast
  • Web Worker
  • Service Worker
  • Shared Worker
  • Browser Extension
  • Node.js
  • WebRTC
  • Electron
  • More transport port

Installation

npm install use-transport data-transport
# or
yarn add use-transport data-transport

Features

  • Simple and responsible
  • Support for multiple transport ports
  • Support for mock transport
  • Full TypeScript support

API

You can use the use-transport hook to create a transport instance. And then use the emit and listen methods to send and receive messages.

import React from 'react';
import { useTransport } from 'use-transport';

const App = () => {
  const transport = useTransport('IFrameMain', {});

  transport.listen(
    'hello',
    async () => {
      return 'world';
    },
    []
  );

  const handleClick = async () => {
    const response = await transport.emit('ping');
    console.log(response);
  };

  return <button onClick={handleClick}>Ping</button>;
};

Parameters

ParameterTypeDescription
typeenumsTransport port type
optionsobjectTransport port options

Returns

ReturnTypeDescription
transport.emit(name: string | options, ...args: any[]) => anyEmit a message
transport.listen(name: string, fn: (...args: any[]) => any, deps?: any[]) => voidListen for a message

The use-transport hook returns a transport instance. more API details can be found in the data-transport documentation.

If you want to use the use-transport hook with TypeScript, you need to use Transport type from use-transport.

type Interaction = {
  listen: {
    foo: (value: number) => Promise<number>;
  };
  emit: {
    bar: (value: number) => Promise<void>;
  };
};

const transport: Transport<Interaction> = useTransport('IFrameMain', {});

License

use-transport is MIT licensed.