{"library":"react-native-sse","title":"React Native Server-Sent Events (SSE) Client","description":"react-native-sse provides a robust, native-friendly `EventSource` implementation for React Native applications, enabling Server-Sent Events (SSE) on both iOS and Android platforms. The current stable version is 1.2.1, with a demonstrated active release cadence focused on features and fixes, as seen in recent minor updates. A key differentiator is its use of `XMLHttpRequest` internally, which eliminates the need for additional native module implementations, simplifying installation and integration. The library fully supports TypeScript, ensuring type safety for event listeners and configuration. It's commonly utilized for real-time data synchronization with systems like Mercure and is compatible with modern streaming APIs, including those used for AI interactions like ChatGPT. Its design prioritizes ease of use and broad compatibility within the React Native ecosystem.","language":"javascript","status":"active","last_verified":"Sun Apr 19","install":{"commands":["npm install react-native-sse"],"cli":null},"imports":["import EventSource from 'react-native-sse';","import { EventSourceListener } from 'react-native-sse';"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import React, { useEffect, useState } from \"react\";\nimport { View, Text, StyleSheet } from \"react-native\";\nimport EventSource, { EventSourceListener } from \"react-native-sse\";\nimport \"react-native-url-polyfill/auto\"; // Use URL polyfill in React Native\n\n// Replace with your actual SSE server URL and token source\nconst SSE_SERVER_URL = \"https://demo.mercure.rocks/.well-known/mercure\";\nconst MOCK_HUB_TOKEN = process.env.MOCK_HUB_TOKEN ?? \"[your-actual-hub-token]\"; // Use process.env for secure token handling\n\ninterface Book {\n  id: number;\n  title: string;\n  isbn: string;\n}\n\nconst BookList: React.FC = () => {\n  const [books, setBooks] = useState<Book[]>([]);\n  const [connectionStatus, setConnectionStatus] = useState<string>(\"Connecting...\");\n  const [error, setError] = useState<string | null>(null);\n\n  useEffect(() => {\n    const url = new URL(SSE_SERVER_URL);\n    url.searchParams.append(\"topic\", \"/book/{bookId}\"); // Example topic\n\n    const es = new EventSource(url.toString(), {\n      headers: {\n        Authorization: {\n          toString: function () {\n            return \"Bearer \" + MOCK_HUB_TOKEN;\n          },\n        },\n      },\n      timeoutBeforeConnection: 5000, // Optional: Timeout for connection attempt\n    });\n\n    const listener: EventSourceListener = (event) => {\n      if (event.type === \"open\") {\n        console.log(\"SSE Connection Opened.\");\n        setConnectionStatus(\"Connected\");\n        setError(null);\n      } else if (event.type === \"message\") {\n        try {\n          const book = JSON.parse(event.data) as Book;\n          setBooks((prevBooks) => {\n            if (!prevBooks.some(b => b.id === book.id)) {\n              return [...prevBooks, book];\n            }\n            return prevBooks;\n          });\n          console.log(`Received book ${book.title}, ISBN: ${book.isbn}`);\n        } catch (parseError) {\n          console.error(\"Failed to parse message data:\", event.data, parseError);\n          setError(\"Failed to parse event data.\");\n        }\n      } else if (event.type === \"error\") {\n        console.error(\"Connection error:\", event.message);\n        setConnectionStatus(\"Disconnected with error\");\n        setError(event.message || \"Unknown connection error\");\n      } else if (event.type === \"exception\") {\n        console.error(\"Internal Error:\", event.message, event.error);\n        setConnectionStatus(\"Disconnected with exception\");\n        setError(event.message || \"Unknown exception\");\n      }\n    };\n\n    es.addEventListener(\"open\", listener);\n    es.addEventListener(\"message\", listener);\n    es.addEventListener(\"error\", listener);\n    es.addEventListener(\"close\", listener); // Listen to close events as well\n\n    return () => {\n      console.log(\"Cleaning up SSE connection.\");\n      es.removeAllEventListeners();\n      es.close();\n    };\n  }, []); // Empty dependency array ensures this runs once on mount/unmount\n\n  return (\n    <View style={styles.container}>\n      <Text style={styles.header}>Book Updates (SSE)</Text>\n      <Text>Status: {connectionStatus}</Text>\n      {error && <Text style={styles.errorText}>Error: {error}</Text>}\n      {books.length === 0 ? (\n        <Text>Waiting for book updates...</Text>\n      ) : (\n        books.map((book) => (\n          <View key={`book-${book.id}`} style={styles.bookItem}>\n            <Text style={styles.bookTitle}>{book.title}</Text>\n            <Text>ISBN: {book.isbn}</Text>\n          </View>\n        ))\n      )}\n    </View>\n  );\n};\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20,\n    backgroundColor: '#f5f5f5',\n  },\n  header: {\n    fontSize: 24,\n    fontWeight: 'bold',\n    marginBottom: 10,\n  },\n  bookItem: {\n    backgroundColor: '#ffffff',\n    padding: 15,\n    borderRadius: 8,\n    marginBottom: 10,\n    shadowColor: '#000',\n    shadowOffset: { width: 0, height: 1 },\n    shadowOpacity: 0.2,\n    shadowRadius: 1.41,\n    elevation: 2,\n  },\n  bookTitle: {\n    fontSize: 18,\n    fontWeight: '600',\n    marginBottom: 5,\n  },\n  errorText: {\n    color: 'red',\n    marginBottom: 10,\n  }\n});\n\nexport default BookList;","lang":"typescript","description":"This example demonstrates how to establish an SSE connection, configure authentication with a Bearer token, listen for `open`, `message`, `error`, and `close` events, parse incoming JSON data, manage component state with real-time updates, and ensure proper connection cleanup in a React Native functional component.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}