### EventSource Initialization and Basic Usage Source: https://github.com/binaryminds/react-native-sse/blob/master/README.md Demonstrates how to initialize EventSource with a URL and set up event listeners for custom events. Includes an example of handling the 'ping' event and accessing Redux state within the listener. ```APIDOC ## POST /binaryminds/react-native-sse ### Description Initializes an EventSource connection to a specified URL and allows for listening to custom server-sent events. This example specifically shows how to use it with React Redux, emphasizing the correct way to access Redux state within event listeners. ### Method POST (or GET, depending on library implementation, but typically initiated with a POST-like setup) ### Endpoint `/binaryminds/react-native-sse` (Conceptual endpoint for library usage) ### Parameters #### Query Parameters - **topic** (string) - Required - The topic to subscribe to. #### Request Body (Not directly applicable for the core EventSource connection setup in this context, but headers and options are configured) ### Request Example ```typescript // Example demonstrating EventSource setup within a React component type CustomEvents = "ping"; const Example: React.FC = () => { const name = useSelector((state: RootState) => state.user.name); const pingHandler: EventSourceListener = useCallback( (event) => { console.log("User name from component selector: ", name); // bad console.log("User name directly from store: ", store.getState().user.name); // good }, [] ); 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); }, []); }; ``` ### Response #### Success Response (200) (EventSource establishes a persistent connection, responses are event-driven) #### Response Example (Event data is received asynchronously via event listeners, e.g., `event.data`) ``` -------------------------------- ### Install react-native-sse with NPM Source: https://github.com/binaryminds/react-native-sse/blob/master/README.md Installs the react-native-sse library using the NPM package manager. This command is an alternative to Yarn for adding the EventSource functionality to a React Native project. ```bash npm install --save react-native-sse ``` -------------------------------- ### Install react-native-sse with Yarn Source: https://github.com/binaryminds/react-native-sse/blob/master/README.md Installs the react-native-sse library using the Yarn package manager. This is the primary method for adding the EventSource functionality to a React Native project. ```bash yarn add react-native-sse ``` -------------------------------- ### SSE Connection with Headers and Topics (TypeScript) Source: https://github.com/binaryminds/react-native-sse/blob/master/README.md An example in TypeScript demonstrating how to establish an SSE connection with custom headers (e.g., Authorization Bearer token) and append query parameters (e.g., 'topic'). It also includes setting up event listeners and managing the connection lifecycle within a React component. ```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([]); 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 ( {books.map((book) => ( {book.title} ISBN: {book.isbn} ))} ); }; export default BookList; ``` -------------------------------- ### Establish SSE Connection and Listeners Source: https://github.com/binaryminds/react-native-sse/blob/master/README.md Shows how to create an EventSource instance, connect to an SSE endpoint, and set up listeners for various events like 'open', 'message', 'error', 'done', and 'close'. Handles different error types within the 'error' event. ```javascript 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("done", (event) => { console.log("Done SSE connection."); }); es.addEventListener("close", (event) => { console.log("Close SSE connection."); }); ``` -------------------------------- ### Use ChatGPT with React Native SSE Source: https://github.com/binaryminds/react-native-sse/blob/master/README.md Demonstrates how to connect to the OpenAI API using Server-Sent Events (SSE) in a React Native application to receive real-time responses from ChatGPT. It includes setting up the EventSource, handling connection events, and processing incoming messages. Requires an OpenAI API key and the react-native-sse library. ```typescript import { useEffect, useState } from "react"; import { Text, View } from "react-native"; import EventSource from "react-native-sse"; const OpenAIToken = '[Your OpenAI token]'; export default function App() { const [text, setText] = useState("Loading..."); useEffect(() => { const es = new EventSource( "https://api.openai.com/v1/chat/completions", { headers: { "Content-Type": "application/json", Authorization: `Bearer ${OpenAIToken}`, }, method: "POST", // Remember to read the OpenAI API documentation to set the correct body body: JSON.stringify({ model: "gpt-3.5-turbo-0125", messages: [ { role: "system", content: "You are a helpful assistant.", }, { role: "user", content: "What is the meaning of life?", }, ], max_tokens: 600, n: 1, temperature: 0.7, stream: true, }), pollingInterval: 0, // Remember to set pollingInterval to 0 to disable reconnections } ); es.addEventListener("open", () => { setText(""); }); es.addEventListener("message", (event) => { if (event.data !== "[DONE]") { const data = JSON.parse(event.data); if (data.choices[0].delta.content !== undefined) { setText((text) => text + data.choices[0].delta.content); } } }); return () => { es.removeAllEventListeners(); es.close(); }; }, []); return ( {text} ); } ``` -------------------------------- ### Import EventSource in JavaScript Source: https://github.com/binaryminds/react-native-sse/blob/master/README.md Demonstrates how to import the EventSource class from the react-native-sse library into a JavaScript file. This is the first step before creating a new EventSource instance. ```javascript import EventSource from "react-native-sse"; ``` -------------------------------- ### EventSource Configuration Options Source: https://github.com/binaryminds/react-native-sse/blob/master/README.md Details the available options for configuring the EventSource connection, including request method, timeouts, credentials, headers, request body, debugging, polling intervals, and line ending characters. ```APIDOC ## EventSource Configuration ### Description Provides an overview of the configuration options available when initializing the `EventSource`. ### Method `new EventSource(url: string | URL, options?: EventSourceOptions)` ### Endpoint N/A (Constructor) ### Parameters #### Options Object (`EventSourceOptions`) - **method** (string) - Optional - Request method. Default: 'GET' - **timeout** (number) - Optional - Time (ms) after which the connection will expire without any activity. Default: 0 (no timeout) - **timeoutBeforeConnection** (number) - Optional - Time (ms) to wait before initial connection is made. Default: 500 - **withCredentials** (boolean) - Optional - Include credentials in cross-site Access-Control requests. Default: false - **headers** (object) - Optional - Your request headers. Default: {} - **body** (any) - Optional - Your request body sent on connection. Default: undefined - **debug** (boolean) - Optional - Show console.debug messages for debugging purpose. Default: false - **pollingInterval** (number) - Optional - Time (ms) between reconnections. If set to 0, reconnections will be disabled. Default: 5000 - **lineEndingCharacter** (string | null) - Optional - Character(s) used to represent line endings in received data. Common values: '\n' for LF (Unix/Linux), '\r\n' for CRLF (Windows), '\r' for CR (older Mac). Default: null (Automatically detect from event) ### Request Example ```typescript const options: EventSourceOptions = { method: 'GET', timeout: 0, timeoutBeforeConnection: 500, withCredentials: false, headers: { 'X-Custom-Header': 'value' }, body: undefined, debug: true, pollingInterval: 5000, lineEndingCharacter: '\n' } ``` ### Response (N/A - This section describes configuration parameters for the constructor.) ``` -------------------------------- ### Advanced TypeScript Usage with Custom Events Source: https://github.com/binaryminds/react-native-sse/blob/master/README.md Illustrates advanced TypeScript features for handling custom events, including defining custom event types, using generic type parameters for specific events, and registering single listeners for multiple event types. ```APIDOC ## EventSource with Custom TypeScript Events ### Description Demonstrates advanced usage of `EventSource` with TypeScript, focusing on defining custom event types and handling them with type safety. Includes examples for listening to specific events and a general listener for all events. ### Method `new EventSource(url: string | URL)` ### Endpoint `https://your-sse-server.com/.well-known/hub` (Example URL) ### Parameters #### Type Definitions - **CustomEvents**: A union type representing all possible custom event names (e.g., `"ping" | "clientConnected"`). #### Event Handling - **`addEventListener(event: keyof CustomEvents | 'open' | 'message', listener: EventSourceListener)`**: Adds a listener for a specific event type. ### Request Example ```typescript import EventSource, { EventSourceListener, EventSourceEvent } from "react-native-sse"; type MyCustomEvents = "ping" | "clientConnected" | "clientDisconnected"; // Listener for all custom events const es = new EventSource( "https://your-sse-server.com/.well-known/hub" ); const listener: EventSourceListener = (event) => { if (event.type === 'open') { console.log("Open SSE connection."); } else if (event.type === 'message') { console.log("Received message:", event.data); } else if (event.type === 'ping') { console.log("Received ping:", event.data); } else if (event.type === 'clientConnected') { console.log("Client connected:", event.data); } else if (event.type === 'clientDisconnected') { console.log("Client disconnected:", event.data); } } es.addEventListener('open', listener); es.addEventListener('message', listener); es.addEventListener('ping', listener); es.addEventListener('clientConnected', listener); es.addEventListener('clientDisconnected', listener); // Listener for a specific event type ('ping') type MySpecificEvents = "ping"; const esSpecific = new EventSource( "https://your-sse-server.com/.well-known/hub" ); const pingListener: EventSourceListener = (event) => { console.log("Received ping with specific type:", event.data); } esSpecific.addEventListener('ping', pingListener); // Alternative syntax for specific event listener const alternativePingListener = (event: EventSourceEvent<'ping', MySpecificEvents>) => { console.log("Received ping with alternative syntax:", event.data); } esSpecific.addEventListener('ping', alternativePingListener); ``` ### Response (EventSource establishes a persistent connection; data is received via the registered listeners.) ``` -------------------------------- ### EventSource Constructor and Options Source: https://github.com/binaryminds/react-native-sse/blob/master/README.md Defines the constructor signature for the EventSource class and details the available configuration options. These options allow customization of connection methods, timeouts, credentials, headers, request body, debugging, polling intervals, and line ending characters. ```typescript new EventSource(url: string | URL, options?: EventSourceOptions); ``` ```typescript const options: EventSourceOptions = { method: 'GET', // Request method. Default: GET timeout: 0, // Time (ms) after which the connection will expire without any activity. Default: 0 (no timeout) timeoutBeforeConnection: 500, // Time (ms) to wait before initial connection is made. Default: 500 withCredentials: false, // Include credentials in cross-site Access-Control requests. Default: false 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. If set to 0, reconnections will be disabled. Default: 5000 lineEndingCharacter: null // Character(s) used to represent line endings in received data. Common values: '\n' for LF (Unix/Linux), '\r\n' for CRLF (Windows), '\r' for CR (older Mac). Default: null (Automatically detect from event) } ``` -------------------------------- ### Manage SSE Connection with React Native App State Source: https://github.com/binaryminds/react-native-sse/blob/master/README.md Provides a JavaScript snippet for managing the lifecycle of a Server-Sent Events (SSE) connection in React Native. It uses the `AppState` API to automatically close the SSE connection when the app enters the background or becomes inactive, and re-opens it when the app returns to the foreground. This helps conserve resources and maintain a stable connection. ```javascript import { useEffect } from 'react'; import { AppState } from 'react-native'; // ... // `es` is your EventSource instance useEffect(() => { const appStateSubscription = AppState.addEventListener('change', (nextAppState) => { if (nextAppState === 'active') { // App became active, reconnect SSE es.open(); } else if (nextAppState === 'background' || nextAppState === 'inactive') { // App went to background, close SSE connection es.close(); } }); return () => { appStateSubscription.remove(); }; }, []); ``` -------------------------------- ### Handling Custom SSE Events with TypeScript Source: https://github.com/binaryminds/react-native-sse/blob/master/README.md Illustrates how to leverage TypeScript generics with EventSource in React Native to handle custom events defined by the server. This includes setting up listeners for specific events like 'ping', 'clientConnected', and 'clientDisconnected', as well as using a single listener for all events. ```typescript import EventSource, { EventSourceListener, EventSourceEvent } from "react-native-sse"; type MyCustomEvents = "ping" | "clientConnected" | "clientDisconnected"; const es = new EventSource( "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); }); ``` ```typescript import EventSource, { EventSourceListener } from "react-native-sse"; type MyCustomEvents = "ping" | "clientConnected" | "clientDisconnected"; const es = new EventSource( "https://your-sse-server.com/.well-known/hub" ); const listener: EventSourceListener = (event) => { if (event.type === 'open') { // connection opened } else if (event.type === 'message') { // ... } else if (event.type === 'ping') { // ... } } es.addEventListener('open', listener); es.addEventListener('message', listener); es.addEventListener('ping', listener); ``` ```typescript import EventSource, { EventSourceListener, EventSourceEvent } from "react-native-sse"; type MyCustomEvents = "ping" | "clientConnected" | "clientDisconnected"; const es = new EventSource( "https://your-sse-server.com/.well-known/hub" ); const pingListener: EventSourceListener = (event) => { // ... } // or const pingListener = (event: EventSourceEvent<'ping', MyCustomEvents>) => { // ... } es.addEventListener('ping', pingListener); ``` -------------------------------- ### React Redux Integration with SSE Source: https://github.com/binaryminds/react-native-sse/blob/master/README.md Demonstrates how to use Server-Sent Events (SSE) within a React Native application that utilizes React Redux. It highlights the importance of accessing Redux state directly from the store within event listeners to ensure up-to-date values, as component props might not reflect the latest state in closures. ```typescript import React, { useCallback, useEffect } from "react"; import { useSelector } from "react-redux"; import EventSource, { EventSourceListener } from "react-native-sse"; type RootState = { user: { name: string; }; }; // Assume 'store' is your Redux store instance, accessible globally or passed appropriately declare const store: { getState: () => RootState; }; type CustomEvents = "ping"; const Example: React.FC = () => { const name = 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: ", name); // bad console.log("User name directly from store: ", store.getState().user.name); // good }, [] ); 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); }, []); return null; // Or any other JSX }; export default Example; ``` -------------------------------- ### Custom SSE Event Interface Source: https://github.com/binaryminds/react-native-sse/blob/master/README.md Defines the TypeScript interface for custom Server-Sent Events (SSE) received by the library. This interface outlines the structure of an event, including its type, data payload, last event ID, and the URL from which it was received, ensuring type safety for event handling. ```typescript export interface CustomEvent { type: E; data: string | null; lastEventId: string | null; url: string; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.