All Projects → binaryminds → react-native-sse

binaryminds / react-native-sse

Licence: MIT license
Event Source implementation for React Native. Server-Sent Events (SSE) for iOS and Android 🚀

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to react-native-sse

Eventsource
EventSource client for Node.js and Browser (polyfill)
Stars: ✭ 541 (+960.78%)
Mutual labels:  sse, eventsource
sseserver
🏄 High-performance Server-Sent Events endpoint for Go
Stars: ✭ 88 (+72.55%)
Mutual labels:  sse, eventsource
Eventsource
A simple Swift client library for the Server Sent Events (SSE)
Stars: ✭ 241 (+372.55%)
Mutual labels:  sse, eventsource
go-sse
Server-Sent Events for Go
Stars: ✭ 106 (+107.84%)
Mutual labels:  sse, event-source
Demo Spring Sse
'Server-Sent Events (SSE) in Spring 5 with Web MVC and Web Flux' article and source code.
Stars: ✭ 102 (+100%)
Mutual labels:  sse, eventsource
Unifrost
Making it easier to push pubsub events directly to the browser.
Stars: ✭ 166 (+225.49%)
Mutual labels:  sse, eventsource
Php Sse
A simple and efficient library implemented HTML5's server-sent events by PHP, is used to real-time push events from server to client, and easier than Websocket, instead of AJAX request.
Stars: ✭ 237 (+364.71%)
Mutual labels:  sse, eventsource
Sse
Server Sent Events server and client for Golang
Stars: ✭ 238 (+366.67%)
Mutual labels:  sse
rust-eventsource-client
Server-sent events (SSE) client implementation for Rust
Stars: ✭ 24 (-52.94%)
Mutual labels:  eventsource
Sse Popcount
SIMD (SSE) population count --- http://0x80.pl/articles/sse-popcount.html
Stars: ✭ 226 (+343.14%)
Mutual labels:  sse
Toys
Storage for my snippets, toy programs, etc.
Stars: ✭ 187 (+266.67%)
Mutual labels:  sse
Boost.simd
Boost SIMD
Stars: ✭ 238 (+366.67%)
Mutual labels:  sse
Turbo-Transpose
Transpose: SIMD Integer+Floating Point Compression Filter
Stars: ✭ 50 (-1.96%)
Mutual labels:  sse
Selenoid Ui
Graphical user interface for Selenoid project
Stars: ✭ 237 (+364.71%)
Mutual labels:  sse
HLML
Auto-generated maths library for C and C++ based on HLSL/Cg
Stars: ✭ 23 (-54.9%)
Mutual labels:  sse
Turbo Run Length Encoding
TurboRLE-Fastest Run Length Encoding
Stars: ✭ 212 (+315.69%)
Mutual labels:  sse
restio
HTTP Client for Dart inspired by OkHttp
Stars: ✭ 46 (-9.8%)
Mutual labels:  sse
go-sse
Fully featured, spec-compliant HTML5 server-sent events library
Stars: ✭ 165 (+223.53%)
Mutual labels:  sse
mu-server
A lightweight modern webserver for Java
Stars: ✭ 31 (-39.22%)
Mutual labels:  sse
ternary-logic
Support for ternary logic in SSE, XOP, AVX2 and x86 programs
Stars: ✭ 21 (-58.82%)
Mutual labels:  sse

React Native EventSource (Server-Sent Events) 🚀

Your missing EventSource implementation for React Native! React-Native-SSE library supports TypeScript.

💿 Installation

We use XMLHttpRequest to establish and handle an SSE connection, so you don't need an additional native Android and iOS implementation. It's easy, just install it with your favorite package manager:

Yarn

yarn add react-native-sse

NPM

npm install --save react-native-sse

🎉 Usage

We are using Server-Sent Events as a convenient way of establishing and handling Mercure connections. It helps us keep data always up-to-date, synchronize data between devices, and improve real-time workflow. Here you have some usage examples:

Import

import EventSource from "react-native-sse";

Connection and listeners

import EventSource from "react-native-sse";

const es = new EventSource("https://your-sse-server.com/.well-known/mercure");

es.addEventListener("open", (event) => {
  console.log("Open SSE connection.");
});

es.addEventListener("message", (event) => {
  console.log("New message event:", event.data);
});

es.addEventListener("error", (event) => {
  if (event.type === "error") {
    console.error("Connection error:", event.message);
  } else if (event.type === "exception") {
    console.error("Error:", event.message, event.error);
  }
});

es.addEventListener("close", (event) => {
  console.log("Close SSE connection.");
});

If you want to use Bearer token and/or topics, look at this example (TypeScript):

import React, { useEffect, useState } from "react";
import { View, Text } from "react-native";
import EventSource, { EventSourceListener } from "react-native-sse";
import "react-native-url-polyfill/auto"; // Use URL polyfill in React Native

interface Book {
  id: number;
  title: string;
  isbn: string;
}

const token = "[my-hub-token]";

const BookList: React.FC = () => {
  const [books, setBooks] = useState<Book[]>([]);

  useEffect(() => {
    const url = new URL("https://your-sse-server.com/.well-known/mercure");
    url.searchParams.append("topic", "/book/{bookId}");

    const es = new EventSource(url, {
      headers: {
        Authorization: {
          toString: function () {
            return "Bearer " + token;
          },
        },
      },
    });

    const listener: EventSourceListener = (event) => {
      if (event.type === "open") {
        console.log("Open SSE connection.");
      } else if (event.type === "message") {
        const book = JSON.parse(event.data) as Book;

        setBooks((prevBooks) => [...prevBooks, book]);

        console.log(`Received book ${book.title}, ISBN: ${book.isbn}`);
      } else if (event.type === "error") {
        console.error("Connection error:", event.message);
      } else if (event.type === "exception") {
        console.error("Error:", event.message, event.error);
      }
    };

    es.addEventListener("open", listener);
    es.addEventListener("message", listener);
    es.addEventListener("error", listener);

    return () => {
      es.removeAllEventListeners();
      es.close();
    };
  }, []);

  return (
    <View>
      {books.map((book) => (
        <View key={`book-${book.id}`}>
          <Text>{book.title}</Text>
          <Text>ISBN: {book.isbn}</Text>
        </View>
      ))}
    </View>
  );
};

export default BookList;

Usage with React Redux

Since the listener is a closure it has access only to the component values from the first render. Each subsequent render has no effect on already defined listeners.

If you use Redux you can get the actual value directly from the store instance.

// full example: https://snack.expo.dev/@quiknull/react-native-sse-redux-example
const Example: React.FC = () => {
    const userName = useSelector((state: RootState) => state.user.name);

    const pingHandler: EventSourceListener = useCallback(
        (event) => {
            // In Event Source Listeners in connection with redux
            // you should read state directly from store object.
            console.log("User name from component selector: ", userName); // bad
            console.log("User name directly from store: ", store.getState().user.name); // good
        },
        [userName]
    );

    useEffect(() => {
        const token = "myToken";
        const url = new URL("https://demo.mercure.rocks/.well-known/mercure");
        url.searchParams.append(
            "topic",
            "https://example.com/my-private-topic"
        );

        const es = new EventSource(url, {
            headers: {
                Authorization: {
                    toString: function () {
                        return "Bearer " + token;
                    }
                }
            }
        });

        es.addEventListener("ping", pingHandler);
    }, []);
};

📖 Configuration

new EventSource(url: string | URL, options?: EventSourceOptions);

Options

const options: EventSourceOptions = {
  method: 'GET'; // Request method. Default: GET
  timeout: 0; // Time after which the connection will expire without any activity: Default: 0 (no timeout)
  headers: {}; // Your request headers. Default: {}
  body: undefined; // Your request body sent on connection: Default: undefined
  debug: false; // Show console.debug messages for debugging purpose. Default: false
  pollingInterval: 5000; // Time (ms) between reconnections. Default: 5000
}

🚀 Advanced usage with TypeScript

Using EventSource you can handle custom events invoked by the server:

import EventSource from "react-native-sse";

type MyCustomEvents = "ping" | "clientConnected" | "clientDisconnected";

const es = new EventSource<MyCustomEvents>(
  "https://your-sse-server.com/.well-known/hub"
);

es.addEventListener("open", (event) => {
  console.log("Open SSE connection.");
});

es.addEventListener("ping", (event) => {
  console.log("Received ping with data:", event.data);
});

es.addEventListener("clientConnected", (event) => {
  console.log("Client connected:", event.data);
});

es.addEventListener("clientDisconnected", (event) => {
  console.log("Client disconnected:", event.data);
});

Custom events always emit result with following interface:

export interface CustomEvent<E extends string> {
  type: E;
  data: string | null;
  lastEventId: string | null;
  url: string;
}

👏 Contribution

If you see our library is not working properly, feel free to open an issue or create a pull request with your fixes.

📄 License

The MIT License

Copyright (c) 2021 Binary Minds

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].