hooks#useSubscription TypeScript Examples

The following examples show how to use hooks#useSubscription. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Provider.tsx    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
useBlocks = () => {
  const { api } = useApi();
  const [blocks, setBlocks] = useState<Blocks>([]);

  const getTime = (timestamp: number) => new Date(timestamp).toLocaleTimeString();

  const getBlock = ({ hash, number }: Header, time: string) => ({
    hash: hash.toHex(),
    number: number.toNumber(),
    time,
  });

  const updateBlocks = (block: Block) => {
    setBlocks((prevBlocks) => {
      const blocksTail = prevBlocks.length > 9 ? prevBlocks.slice(0, -1) : prevBlocks;
      return [block, ...blocksTail];
    });
  };

  const handleSubscription = (header: Header) =>
    api.blocks
      .getBlockTimestamp(header.hash)
      .then((timestamp) => getTime(timestamp.toNumber()))
      .then((time) => getBlock(header, time))
      .then(updateBlocks);

  const subscribeToBlocks = () => api.gearEvents.subscribeToNewBlocks(handleSubscription);
  useSubscription(subscribeToBlocks);

  return blocks;
}