/use-mercure

A hook to easily integrate Mercure in a React application

Primary LanguageTypeScriptMIT LicenseMIT

@liinkiing/use-mercure

Version Downloads/week License

A hook to integrate Mercure EventSource in React.

Installation

With yarn

$ yarn add @liinkiing/use-mercure

With npm

$ npm i @liinkiing/use-mercure

Example

import React, { useState } from 'react';
import { MercureProvider, useMercure } from '@liinkiing/use-mercure';

interface MessageFromMercure {
  readonly id: string;
  readonly body: string;
}

type Messages = readonly MessageFromMercure[];

const Example: React.FC = () => {
  const [messages, setMessages] = useState<Messages>([]);

  // By using TypeScript generics, you have type-safety for the
  // data coming from your Mercure hub
  useMercure<MessageFromMercure>('http://example.com/topic', message => {
    setMessages([...messages, message]);
  }, [messages]); // array of deps

  return messages.length ? (
    <ul>
      {messages.map(message => (
        <li key={message.id}>{message.body}</li>
      ))}
    </ul>
  ) : (
    <p>No messages...</p>
  );
};

const App: React.FC = () => (
  <MercureProvider
    options={{
      hubUrl: 'http://yourmercure.hub/.well-known/mercure',
      withCredentials: true /* default to false */,
    }}
  >
    <Example />
  </MercureProvider>
);