use-api-poller-worker
TypeScript icon, indicating that this package has built-in type declarations

1.0.2 • Public • Published

use-api-poller-worker

codecov CircleCI npm version

React hook for api-poller-worker

use-api-poller-worker is a React hook that you can use to integrate api-poller-worker into your React app.

Table of contents

⇡ Top

Installation

npm install use-api-poller-worker
⇡ Top

Usage

This hook takes the same options as the ApiPollerWorker class from api-poller-worker, plus an extra callback argument which will be called when the underlying worker emits a message.

It's recommended to wrap your callback in React.useCallback, so that your app does not unnecessarily re-render multiple times.

const MyComponent = () => {
  const [items, setItems] = React.useState<Item>(null);
  const callback = React.useCallback<(data: Msg<Item>) => void>(data => {
    setItems(data);
  }, [setItems]);
 
  useApiPollerWorker<Item>({
    workerUrl: '<my api endpoint>',
  }, callback);
 
  return {
    <div>
      {items}
    </div>
  };
};
⇡ Top

API

Functions

useApiPollerWorker

This is the default export.

import useApiPollerWorker from 'use-api-poller-worker';
 
function useApiPollerWorker<T extends {}>(
  options: ApiPollerWorkerOptions,
  callback: (data: Msg<T>) => void,
)

Both ApiPollerWorkerOptions and Msg<T> come from api-poller-worker. You might want to import Msg<T> for type safety. This library re-exports Msg<T> for convenience.

useApiPollerWorker also accepts a generic, T for the type of resource you're polling.

⇡ Top

Types

Msg<T>

Represents the contents of a message from the underlying polling library.

import { Msg } from 'use-api-poller-worker';
interface Msg<T> {
  newItems: Records<T>;
  updatedItems: Records<T>;
  removedItems: string[];
}
⇡ Top

Package Sidebar

Install

npm i use-api-poller-worker

Weekly Downloads

0

Version

1.0.2

License

MIT

Unpacked Size

7.46 kB

Total Files

5

Last publish

Collaborators

  • brianmcallister