### Manual Android Installation: settings.gradle Source: https://github.com/avishayil/react-native-restart/blob/master/README.md Add this to your android/settings.gradle file for manual Android installation. ```gradle include ':react-native-restart' project(':react-native-restart').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-restart/android') ``` -------------------------------- ### Manual Android Installation: MainApplication.java Source: https://github.com/avishayil/react-native-restart/blob/master/README.md Register the RestartPackage in your MainApplication.java file for manual Android installation. ```java import com.reactnativerestart.RestartPackage; // <--- Import public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { ...... /** * A list of packages used by the app. If the app uses additional views * or modules besides the default ones, add more packages here. */ @Override protected List getPackages() { ... return Arrays.asList( new MainReactPackage(), new RestartPackage() // Add this line ); } }; ...... }; ``` -------------------------------- ### Install iOS Pods Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Navigate to the ios directory and install CocoaPods dependencies. ```bash cd ios && pod install ``` -------------------------------- ### Manual Android Installation: build.gradle Source: https://github.com/avishayil/react-native-restart/blob/master/README.md Add this to your android/app/build.gradle file's dependencies block for manual Android installation. ```gradle implementation project(':react-native-restart') ``` -------------------------------- ### Install iOS CocoaPods Dependencies Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Navigate to the iOS directory and run 'pod install' to install the react-native-restart pod and its dependencies. ```bash cd ios pod install cd .. ``` -------------------------------- ### Verify react-native-restart installation Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md After installation, run this command to check if the package files are present in your node_modules directory. ```bash # Check that the package is installed ls node_modules/react-native-restart ``` -------------------------------- ### Install with NPM Source: https://github.com/avishayil/react-native-restart/blob/master/README.md Use this command to add the package to your project when using NPM. ```bash npm install --save react-native-restart ``` -------------------------------- ### Troubleshoot iOS Pod Installation Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md If 'pod install' fails, clear the Pods cache, remove Podfile.lock, update pod repositories, and try installing again. ```bash # Clear pod cache rm -rf Pods rm Podfile.lock # Update pod repositories pod repo update # Try again pod install ``` -------------------------------- ### Usage Example for RNRestart Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/TYPES.md Demonstrates how to import and use the RNRestart module, conforming to the RestartType interface, for restarting the application and getting the restart reason. ```typescript import RNRestart from 'react-native-restart'; // RNRestart conforms to RestartType const restartModule: RestartType = RNRestart; // Using the methods RNRestart.restart('config_update'); RNRestart.getReason().then(reason => { console.log('Last restart reason:', reason); }); ``` -------------------------------- ### Install with Yarn Source: https://github.com/avishayil/react-native-restart/blob/master/README.md Use this command to add the package to your project when using Yarn. ```bash yarn add react-native-restart ``` -------------------------------- ### iOS Auto-Linking Setup Source: https://github.com/avishayil/react-native-restart/blob/master/README.md Run this command in the ios directory to link the native dependencies for iOS. ```bash cd ios pod install ``` -------------------------------- ### Verify TypeScript Types Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Example demonstrating how to import the module and verify that TypeScript recognizes its types. ```typescript import RNRestart from 'react-native-restart'; // TypeScript will recognize the type const reason: Promise = RNRestart.getReason(); ``` -------------------------------- ### Start Metro Bundler Source: https://github.com/avishayil/react-native-restart/blob/master/Example/README.md Starts the Metro JavaScript bundler, which is essential for React Native development. Run this from the root of your project. ```sh # Using npm npm start # OR using Yarn yarn start ``` -------------------------------- ### Check Java Version Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Verify the installed Java Development Kit version. Version 17 or higher is recommended. ```bash java -version ``` -------------------------------- ### Install react-native-restart using npm Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Use this command to add the package to your project when using npm as your package manager. ```bash cd your-react-native-project npm install --save react-native-restart ``` -------------------------------- ### Provide User Feedback During Restart Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/ERRORS.md This example demonstrates how to provide user feedback (loading indicator, error messages) during an app restart initiated by the user. It includes platform-specific handling for Windows. ```javascript async function userInitiatedRestart() { showLoadingIndicator(); try { // On iOS and Android, this returns immediately RNRestart.restart('user_initiated'); // On Windows, wait for promise if (Platform.OS === 'windows') { await RNRestart.restart('user_initiated'); } } catch (error) { hideLoadingIndicator(); showErrorMessage('Failed to restart app: ' + error.message); } } ``` -------------------------------- ### Install CocoaPods Dependencies Source: https://github.com/avishayil/react-native-restart/blob/master/Example/README.md Installs CocoaPods dependencies required for building iOS applications. Run this after cloning the project or updating native dependencies. ```sh bundle install bundle exec pod install ``` -------------------------------- ### Install react-native-restart using yarn Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Use this command to add the package to your project when using yarn as your package manager. ```bash cd your-react-native-project yarn add react-native-restart ``` -------------------------------- ### Verify Package Installation Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Check if the react-native-restart package is present in your node_modules directory. ```bash ls node_modules/react-native-restart ``` -------------------------------- ### Example Usage of RNRestart Methods Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/TYPES.md Demonstrates how to import and use the RNRestart module to trigger an app restart with a specific reason and to retrieve the reason for a previous restart. ```typescript import RNRestart from 'react-native-restart'; function handleUpdateCheck(hasUpdate: boolean) { if (hasUpdate) { RNRestart.restart('version_update'); } } async function checkRestartReason() { const reason: string | null = await RNRestart.getReason(); if (reason === 'version_update') { console.log('App was updated and restarted'); } } ``` -------------------------------- ### Check CocoaPods Version Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Verify the installed version of CocoaPods. ```bash pod --version ``` -------------------------------- ### Consumer Type Safety Example Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/TYPES.md Demonstrates correct and incorrect usage of the 'restart' and 'getReason' methods based on TypeScript type checking. ```typescript import RNRestart from 'react-native-restart'; // TypeScript knows RNRestart conforms to RestartType RNRestart.restart('reason'); // ✓ Correct RNRestart.restart(); // ✓ Correct (reason is optional) RNRestart.restart(123); // ✗ Type error: argument of type 'number' is not assignable to parameter of type 'string' RNRestart.someOtherMethod(); // ✗ Type error: property 'someOtherMethod' does not exist on type 'RestartType' RNRestart.getReason().then(reason => { if (typeof reason === 'string') { console.log('Reason:', reason); } }); ``` -------------------------------- ### CocoaPod iOS Installation in Podfile Source: https://github.com/avishayil/react-native-restart/blob/master/README.md Configure your ios/Podfile to use react-native-restart from local node_modules. ```ruby target 'MyReactApp' do # Make sure you're also using React-Native from ../node_modules pod 'React', :path => '../node_modules/react-native', :subspecs => [ 'Core', 'RCTActionSheet', # ... whatever else you use ] # React-Native dependencies such as yoga: pod 'yoga', path: '../node_modules/react-native/ReactCommon/yoga' # The following line uses react-native-restart, linking with # the library and setting the Header Search Paths for you pod 'react-native-restart', :path => '../node_modules/react-native-restart' end ``` -------------------------------- ### Get App Restart Reason with Promise Chaining Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/TYPES.md This snippet demonstrates how to get the app's restart reason using Promise chaining. It includes a .then() block for handling the reason and a .catch() block for errors. ```typescript import RNRestart from 'react-native-restart'; // With Promise chaining function processRestartReason2() { return RNRestart.getReason() .then(reason => { if (reason) { handleRestartReason(reason); } }) .catch(error => { console.error('Failed to get restart reason:', error); }); } ``` -------------------------------- ### RestartModule Constructor Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/AndroidImplementation.md The constructor for the RestartModule. It accepts the ReactApplicationContext and initializes the base class. No additional setup is required within the constructor itself. ```java public RestartModule(ReactApplicationContext reactContext) { super(reactContext); } ``` -------------------------------- ### Handle getReason Promise with async/await Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/ERRORS.md An alternative to .then/.catch, this async/await example demonstrates how to handle the promise returned by RNRestart.getReason() within a try-catch block for cleaner error handling. ```javascript // ✓ Or with async/await async function checkReason() { try { const reason = await RNRestart.getReason(); if (reason) { handleRestartReason(reason); } } catch (error) { console.error('Error getting restart reason:', error); } } ``` -------------------------------- ### JavaScript Error Handling for Windows Restart Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/ERRORS.md This JavaScript example demonstrates how to safely call the restart function on Windows and handle potential errors. It specifically checks for the 'restart request rejected.' message to inform the user if the app is not in the foreground. ```javascript import RNRestart from 'react-native-restart'; async function safeRestartOnWindows() { try { await RNRestart.restart('reason'); // If this point is reached, restart was initiated } catch (error) { if (error.message === 'restart request rejected.') { console.warn('App is not in foreground. Please bring app to foreground and try again.'); } else { console.error('Restart failed with system error:', error); } } } ``` -------------------------------- ### Bridge Initialization and Restart Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/iOSImplementation.md Initializes an RCTBridge and calls the restart method with a reason. This is an example of manual testing from Swift. ```Swift // From Swift bridge test code RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self]; NSMutableDictionary *args = [[NSMutableDictionary alloc] init]; args[@"reason"] = @"test_restart"; [bridge.module restartWithReason:args[@"reason"]]; ``` -------------------------------- ### Reset React Native Cache Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Start the React Native packager with the reset cache option. ```bash npx react-native start --reset-cache ``` -------------------------------- ### Handle getReason Promise with .then/.catch Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/ERRORS.md Always handle the promise returned by RNRestart.getReason() to avoid unhandled rejections. This example shows how to use .then() and .catch() for proper error management. ```javascript // ✗ Don't do this RNRestart.getReason(); // Unhandled promise // ✓ Do this RNRestart.getReason() .then(reason => { if (reason) { handleRestartReason(reason); } }) .catch(error => { console.error('Error getting restart reason:', error); }); ``` -------------------------------- ### Build and Run iOS App Source: https://github.com/avishayil/react-native-restart/blob/master/Example/README.md Builds and runs the React Native application on an iOS simulator or device. Ensure Metro is running in another terminal and CocoaPods are installed. ```sh # Using npm npm run ios # OR using Yarn yarn ios ``` -------------------------------- ### JavaScript Error Handling for getReason Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/ERRORS.md This JavaScript example demonstrates how to handle potential errors when calling the RNRestart.getReason() method using both async/await with try/catch and Promise chaining with .catch(). ```javascript import RNRestart from 'react-native-restart'; async function safeGetRestartReason() { try { const reason = await RNRestart.getReason(); console.log('Restart reason:', reason); } catch (error) { // Error code: "Create Event Error" console.error('Failed to retrieve restart reason:', error); // Handle the error gracefully } } // Or with Promise chaining RNRestart.getReason() .then(reason => { console.log('Restart reason:', reason); }) .catch(error => { console.error('Error code:', error.code); // "Create Event Error" console.error('Error message:', error.message); }); ``` -------------------------------- ### Safe Usage of Restart on iOS Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/ERRORS.md On iOS, errors are not reported to JavaScript. This example shows the standard way to call the restart method, understanding that failure means the app simply won't restart. ```swift // iOS: Errors are not reported, so always safe to call RNRestart.restart('reason'); // If something fails, the app simply does not restart ``` -------------------------------- ### Get Restart Reason with Async/Await Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/USAGE_PATTERNS.md Use this snippet to retrieve the reason for the last app restart using async/await syntax. It handles potential errors during the retrieval process. ```typescript import React, { useEffect, useState } from 'react'; import { View, Text } from 'react-native'; import RNRestart from 'react-native-restart'; function RestartReasonDisplay() { const [reason, setReason] = useState(null); useEffect(() => { async function getLastRestartReason() { try { const restartReason = await RNRestart.getReason(); setReason(restartReason); } catch (error) { console.error('Failed to get restart reason:', error); } } getLastRestartReason(); }, []); return ( {reason && ( App was restarted for: {reason} )} {!reason && ( First app startup (no restart reason) )} ); } export default RestartReasonDisplay; ``` -------------------------------- ### Restart on Logout Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/USAGE_PATTERNS.md Use this pattern to fully reload the application after a user logs out. This ensures all authentication-related states and data are cleared and the app starts fresh in a logged-out state. Pass a reason string for debugging. ```typescript import RNRestart from 'react-native-restart'; async function handleLogout() { try { // Clear authentication tokens await clearAuthTokens(); // Clear sensitive data await clearUserPreferences(); // Restart to reload app in logged-out state RNRestart.restart('user_logout'); } catch (error) { console.error('Logout failed:', error); } } async function handleSessionExpired() { // Session expired; restart to refresh RNRestart.restart('session_expired'); } async function handleAuthError() { // Authentication error; restart to retry RNRestart.restart('auth_error_recovery'); } ``` -------------------------------- ### Conditional State Reset on App Initialization Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/USAGE_PATTERNS.md Integrate restart logic into your app's initialization process. This example shows how to conditionally reset application state based on the restart reason, such as 'logout' or 'version_update'. ```typescript import React, { useEffect } from 'react'; import { useAppState } from '@react-native-camera/camera'; import RNRestart from 'react-native-restart'; import * as Redux from 'react-redux'; function AppInitializer() { const dispatch = Redux.useDispatch(); useEffect(() => { async function initializeApp() { const restartReason = await RNRestart.getReason(); // Reset state only for specific restart reasons if (restartReason === 'logout') { dispatch(resetAppState()); dispatch(clearUserData()); } else if (restartReason === 'version_update') { dispatch(runMigrations()); } // Always reset cache dispatch(clearCache()); } initializeApp(); }, [dispatch]); return null; } export default AppInitializer; ``` -------------------------------- ### Build Windows App Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Command to build the Windows application after setting up the native project. ```bash npx react-native run-windows ``` -------------------------------- ### Get Restart Reason with Promise Chaining Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/USAGE_PATTERNS.md This snippet demonstrates how to get the restart reason using Promise chaining. It includes conditional logic to perform different actions based on the restart reason. ```typescript import RNRestart from 'react-native-restart'; function checkRestartReason() { RNRestart.getReason() .then(reason => { if (reason === 'crash_recovery') { showCrashRecoveryNotification(); } else if (reason === 'version_update') { showVersionUpdateMessage(); } else if (reason) { console.log('App restarted for reason:', reason); } }) .catch(error => { console.error('Error getting restart reason:', error); }); } ``` -------------------------------- ### Initiate App Restart on Windows Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/WindowsImplementation.md This C++ snippet demonstrates how to request an app restart on Windows using `CoreApplication::RequestRestartAsync`. It handles potential failure reasons and resolves or rejects a provided promise accordingly. Use this when initiating a restart from native code. ```cpp static IAsyncAction RequestRestartAsync(ReactPromise promise) { auto capturedPromise = promise; auto reason = co_await CoreApplication::RequestRestartAsync(L""); if (reason == AppRestartFailureReason::NotInForeground || reason == AppRestartFailureReason::Other) { capturedPromise.Reject("restart request rejected."); } capturedPromise.Resolve(); } ``` -------------------------------- ### Call Restart from JavaScript and Verify Reason Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/AndroidImplementation.md Demonstrates how to trigger a restart from JavaScript and then verify the restart reason on the subsequent application startup. Ensure the `RNRestart` module is correctly imported and registered. ```java RNRestart.restart('test_reason'); // Verify on next startup RNRestart.getReason().then(reason => { assert(reason === 'test_reason'); }); ``` -------------------------------- ### Initiate App Restart on Windows Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/WindowsImplementation.md Demonstrates how to programmatically trigger an application restart on Windows when the app is in the foreground. Handles the promise returned by the restart function, logging success or failure. ```javascript // When app is in foreground RNRestart.Restart() .then(() => console.log('Restart initiated')) .catch(e => console.error('Restart failed:', e)); ``` -------------------------------- ### Simulator URL Open Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/iOSImplementation.md Opens a URL on the simulator to trigger a restart. This is used for simulator testing. ```bash # Run on simulator xcrun simctl openurl booted http://localhost:8081/restart ``` -------------------------------- ### Clean and Build Android Project Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Perform a Gradle clean and build from the android directory to apply manual linking changes. ```bash # From project root cd android ./gradlew clean ./gradlew build cd .. ``` -------------------------------- ### Type Hierarchy Overview Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/TYPES.md Illustrates the main export 'RestartType' and its methods, alongside the internal 'NativeModule' types. ```plaintext RestartType (main export) ├─ Restart: (reason?: string) => void [DEPRECATED] ├─ restart: (reason?: string) => void [PREFERRED] └─ getReason: () => Promise NativeModule (internal) ├─ Restart: (reason: string | null) => void ├─ restart: (reason: string | null) => void └─ getReason: () => Promise ``` -------------------------------- ### Build iOS App Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Build and run the iOS application using the react-native CLI. ```bash npx react-native run-ios ``` -------------------------------- ### Registering a Reload Listener Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/iOSImplementation.md Example of how to register a listener for React Native reload commands. This listener can then handle restart events. ```Objective-C // Listeners registered elsewhere in React Native framework // get called with message: @"react-native-restart: Restart" [RCTReloadCommand addReloadCommandListener:^(NSString *reason) { if ([reason containsString:@"react-native-restart"]) { // Handle restart } }]; ``` -------------------------------- ### Get Restart Reason Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Retrieve the reason for the last restart using the getReason function from the RNRestart module. This function returns a Promise. ```javascript RNRestart.getReason() ``` -------------------------------- ### Build Android App Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Build and run the Android application using the react-native CLI. ```bash npx react-native run-android ``` -------------------------------- ### Test Foreground Requirement for Restart on Windows Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/WindowsImplementation.md Illustrates the foreground requirement for initiating a restart on Windows. If the app is not in the foreground (e.g., minimized), the restart call is expected to be rejected. ```javascript // Minimize app, then call restart // Should reject with "restart request rejected." ``` -------------------------------- ### Get Static React Instance Manager Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/AndroidImplementation.md Retrieves the ReactInstanceManager from a static holder. Returns null if the holder is not initialized. This is an internal method used by resolveInstanceManager. ```java static ReactInstanceManager getReactInstanceManager() // Behavior: if (mReactInstanceHolder == null) { return null; } return mReactInstanceHolder.getReactInstanceManager(); ``` -------------------------------- ### Android Native Module - Get Reason Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/ARCHITECTURE.md Asynchronously retrieves the stored restart reason from the Android native module. This method is exported to the JavaScript layer. ```java @ReactMethod public void getReason(Promise promise) { promise.resolve(restartReason); } ``` -------------------------------- ### Clean Android Gradle Build Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Navigate to the android directory and execute the Gradle clean task. ```bash cd android ./gradlew clean cd .. ``` -------------------------------- ### restart Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/AndroidImplementation.md Initiates a restart of the application with an optional reason. This method is identical in behavior to the `Restart(String reason)` method. ```APIDOC ## restart(String reason) ### Description Initiates a restart of the application with an optional reason. This method is identical in behavior to the `Restart(String reason)` method. ### Method @ReactMethod ### Parameters #### Path Parameters - **reason** (String) - Optional - Optional reason for the restart ### Return Type void ### Throws No exceptions. ``` -------------------------------- ### Handle Windows Restart Promise Rejection Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/ERRORS.md This snippet shows how to handle potential promise rejections when calling RNRestart.restart() on Windows, which may occur if the app is not in the foreground. It uses async/await with a try-catch block. ```javascript // ✓ Handle potential rejection on Windows async function restartApp(reason) { try { await RNRestart.restart(reason); } catch (error) { // On Windows, this may reject if app is not in foreground console.warn('Restart failed:', error.message); } } // Or simply ignore if not on Windows RNRestart.restart(reason); // Safe on iOS and Android ``` -------------------------------- ### Export Method with Multiple Parameters Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/iOSImplementation.md Exports an Objective-C method with multiple parameters to the JavaScript bridge. This example shows exporting a method named 'method' that accepts an NSString and an NSNumber. ```objc RCT_EXPORT_METHOD(method: (NSString *)param1 withValue: (NSNumber *)param2) { ... } ``` -------------------------------- ### Typical tsconfig.json Configuration Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md A standard tsconfig.json configuration that should work with the package. ```json { "compilerOptions": { "target": "ES2020", "module": "commonjs", "lib": ["ES2020"], "jsx": "react-native", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true } } ``` -------------------------------- ### Graceful Degradation with Module Check Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/ERRORS.md Implement graceful degradation by checking if the react-native-restart module is available before attempting to use its functions. This prevents runtime errors on platforms where it might not be supported or installed. ```javascript // Check if module is available before calling import { NativeModules, Platform } from 'react-native'; function canRestart() { return NativeModules.RNRestart !== undefined; } function restartIfAvailable(reason) { if (canRestart()) { RNRestart.restart(reason); } else { console.warn('react-native-restart is not available'); // Implement fallback behavior } } ``` -------------------------------- ### Verify React Native Restart Package Info Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Use this command to check information about the react-native-restart package, specifically related to its React Native compatibility. ```bash npm info react-native-restart | grep -A 5 react-native ``` -------------------------------- ### Export Method with Single Parameter Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/iOSImplementation.md Exports an Objective-C method to the JavaScript bridge. This example shows exporting a method named 'restart' that accepts a single NSString parameter named 'reason'. ```objc RCT_EXPORT_METHOD(restart: (NSString *)reason) { ... } ``` -------------------------------- ### Rebuild Native Code for iOS Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Reinstall pods and then run the iOS application to rebuild native code. ```bash cd ios && pod install && cd .. && npx react-native run-ios ``` -------------------------------- ### Get App Restart Reason with Async/Await Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/TYPES.md Use this snippet to retrieve the reason for the app's last restart using async/await. It handles both successful resolution with a reason string and potential errors. ```typescript import RNRestart from 'react-native-restart'; // With async/await async function processRestartReason() { try { const reason = await RNRestart.getReason(); if (reason) { console.log(`App restarted for: ${reason}`); handleRestartReason(reason); } } catch (error) { console.error('Failed to get restart reason:', error); } } ``` -------------------------------- ### Platform-Specific Restart Logic Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/USAGE_PATTERNS.md Handles restarts differently for Windows (async) versus iOS/Android (sync). Ensure proper error handling for the asynchronous Windows restart. ```typescript import RNRestart from 'react-native-restart'; import { Platform } from 'react-native'; async function platformSpecificRestart(reason: string) { if (Platform.OS === 'windows') { // Windows uses async API; must handle promise try { await RNRestart.restart(reason); } catch (error) { if (error.message === 'restart request rejected.') { console.warn('Restart failed: app not in foreground'); } else { console.error('Restart failed:', error); } } } else { // iOS and Android: synchronous operation RNRestart.restart(reason); } } ``` -------------------------------- ### restart: Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/iOSImplementation.md Preferred method to trigger a bundle reload with an optional reason. It ensures the reload command is executed on the main thread. ```APIDOC ## restart: ### Description Preferred method to trigger a bundle reload with an optional reason. It ensures the reload command is executed on the main thread. ### Method Objective-C Instance Method (Exported as `restart` from JavaScript) ### Parameters #### Path Parameters - **reason** (NSString*) - Optional - Optional reason for the restart; can be nil ### Return Type void ### Behavior 1. Stores the provided reason. 2. Checks if the current thread is the main thread. 3. If not on the main thread, dispatches the `loadBundle` call to the main queue synchronously. 4. Calls `loadBundle` to trigger the reload. 5. Returns void immediately to JavaScript. ### Thread Safety - Main thread enforcement: Yes, via dispatch_sync ### Preferred Yes; new code should use this instead of `Restart:` ``` -------------------------------- ### Registering RestartPackage in MainApplication Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/AndroidImplementation.md Add the RestartPackage to the list of React packages in your MainApplication.java file to integrate the module. This is required for manual linking. ```java import com.reactnativerestart.RestartPackage; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override protected List getPackages() { return Arrays.asList( new MainReactPackage(), new RestartPackage() // <-- Add here ); } }; } ``` -------------------------------- ### Verify Restart Reason in Testing Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/USAGE_PATTERNS.md This function retrieves the reason for the last application restart and checks if it starts with a specific prefix, indicating it was triggered by an end-to-end test. This is useful for validating restart behavior during automated testing. ```typescript import RNRestart from 'react-native-restart'; import { Platform } from 'react-native'; export async function verifyRestartReason() { try { const reason = await RNRestart.getReason(); const isE2ERestart = reason?.startsWith('e2e_test_'); console.log('E2E Restart verification:', { lastReason: reason, isE2ERestart, }); return isE2ERestart; } catch (error) { console.error('Restart reason verification failed:', error); return false; } } ``` -------------------------------- ### Android Get Reason Method Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/AndroidImplementation.md Use this method to retrieve the reason for the last application restart. It resolves a React Native promise with the stored reason or null if no restart has occurred. Errors during retrieval are caught and rejected. ```java @ReactMethod public void getReason(Promise promise) ``` ```java try { promise.resolve(restartReason); } catch(Exception e) { promise.reject("Create Event Error", e); } ``` -------------------------------- ### Clean iOS Build Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Clean the iOS build artifacts. ```bash xcode-build clean ``` -------------------------------- ### getReason() Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/RNRestart.md Retrieves the reason string from the most recent application restart. This method returns a Promise that resolves to the reason string provided to `restart()` or `Restart()`, or `null` if no reason was given. ```APIDOC ## getReason() ### Description Retrieves the reason string from the most recent application restart. ### Method `getReason(): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import RNRestart from 'react-native-restart'; async function checkRestartReason() { try { const reason = await RNRestart.getReason(); if (reason) { console.log('App was restarted with reason:', reason); } else { console.log('App was restarted without a reason'); } } catch (error) { console.error('Error retrieving restart reason:', error); } } checkRestartReason(); ``` ### Response #### Success Response (200) - **Promise** - Resolves to the reason string passed to the most recent `restart()` or `Restart()` call. If no reason was provided, resolves to `null` or `undefined`. #### Response Example ```json "user_requested_reload" ``` ### Error Handling - No rejection cases documented. ``` -------------------------------- ### Load Bundle with Primary Restart Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/AndroidImplementation.md Clears lifecycle listeners and attempts to recreate the React context in the background using the instance manager. Falls back to loadBundleLegacy if the instance manager is not found or recreation fails. Uses Handler to ensure main thread execution. ```java private void loadBundle() // Behavior: // 1. Cleanup: Clears existing lifecycle listeners via clearLifecycleEventListener() // 2. Instance Manager Resolution: Calls resolveInstanceManager() // 3. Primary Restart: If instance manager found: new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { try { instanceManager.recreateReactContextInBackground(); } catch (Throwable t) { loadBundleLegacy(); // Fallback } } }); // 4. Fallback: If instance manager not found, calls loadBundleLegacy() ``` -------------------------------- ### Reinstall Dependencies Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Reinstall project dependencies using npm or yarn. ```bash npm install ``` ```bash yarn install ``` -------------------------------- ### RNRestart Module (Windows) Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/NativeModuleInterface.md Documentation for the RNRestart native module on Windows, which allows triggering application restarts. ```APIDOC ## RNRestart Module (Windows) **Module Name:** `RNRestart` **Language:** C++/WinRT ### Exported Methods #### Restart(ReactPromise promise) Initiates an asynchronous restart request for the application. **Parameters:** | Parameter | Type | Description | |-----------|------|-------------| | promise | ReactPromise | React Native promise for async result handling | **Behavior:** - Initiates an async restart request via `RequestRestartAsync(promise)`. - Attaches a completion handler to the async operation. - Returns immediately as the operation is asynchronous. **Promise Resolution:** - Resolves when the restart is successfully initiated. - Rejects if the restart is rejected (e.g., not in foreground or other errors). ``` -------------------------------- ### Load Bundle Legacy Fallback Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/AndroidImplementation.md Provides a fallback restart mechanism by recreating the current activity. This is used when modern context recreation fails or is incompatible. It is more disruptive and may lose transient state. ```java private void loadBundleLegacy() // Behavior: // 1. Gets the current Activity: getCurrentActivity() // 2. If activity is available, runs on UI thread: currentActivity.runOnUiThread(new Runnable() { @Override public void run() { currentActivity.recreate(); } }); ``` -------------------------------- ### Restart on Theme Change Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/USAGE_PATTERNS.md Apply theme changes throughout the entire application by restarting it. This is useful for ensuring that all components and styles update correctly after a theme preference is modified. A reason string is recommended. ```typescript import RNRestart from 'react-native-restart'; import { useTheme } from '@react-navigation/native'; function SettingsThemeToggle() { const { colors } = useTheme(); async function handleThemeChange(newTheme: 'light' | 'dark' | 'auto') { // Save new theme preference await saveThemeSetting(newTheme); // Restart to apply theme throughout app RNRestart.restart('theme_changed'); } return ( // Theme selection buttons... ); } ``` -------------------------------- ### Context API Integration for App Restart Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/USAGE_PATTERNS.md Provides a React Context for managing and triggering app restarts. Includes a provider component and a hook to consume the restart function. Assumes `RestartContext` is defined. ```typescript import React, { createContext, useCallback } from 'react'; import RNRestart from 'react-native-restart'; const RestartContext = createContext<{ restart: (reason: string) => void; }>(null); export function RestartProvider({ children }) { const handleRestart = useCallback((reason: string) => { RNRestart.restart(reason); }, []); return ( {children} ); } export function useRestart() { return React.useContext(RestartContext); } ``` -------------------------------- ### JavaScript Interface Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/NativeModuleInterface.md Defines the methods available on the NativeModuleInterface for interacting with the native restart functionality. ```APIDOC ## JavaScript Interface ### Type Definitions ```typescript type RestartType = { /** * @deprecated use `restart` instead */ Restart(): void; restart(): void; getReason(): Promise; }; ``` ### Method Details - **restart()**: Initiates an application restart. This method is synchronous in JavaScript. - **getReason()**: Retrieves the reason for the last application restart. This method is asynchronous and returns a Promise in JavaScript. ``` -------------------------------- ### Windows Restart Request Flow Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/WindowsImplementation.md Illustrates the asynchronous flow of RequestRestartAsync() on Windows, including success and failure paths with specific rejection reasons. ```text RequestRestartAsync() ↓ Windows API: CoreApplication.RequestRestartAsync() ↓ ├─→ Success → Resolve promise │ └─→ Failure → Check reason ├─→ NotInForeground → Reject: "restart request rejected." ├─→ Other → Reject: "restart requestμία rejected." └─→ Async operation error → MakeAsyncActionCompletedHandler └─→ Reject: HRESULT error message ``` -------------------------------- ### restart() Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/RNRestart.md Restarts the React Native application bundle. An optional reason string can be provided to describe why the restart was triggered, which can be retrieved later using `getReason()`. ```APIDOC ## restart() ### Description Restarts the React Native application bundle with an optional reason string. ### Method `restart(reason?: string): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **reason** (string) - Optional - Description: Optional reason string describing why the restart was triggered. This string is stored and can be retrieved via `getReason()`. ### Request Example ```javascript import RNRestart from 'react-native-restart'; // Simple restart without reason RNRestart.restart(); // Restart with reason RNRestart.restart('user_requested_reload'); ``` ### Response #### Success Response (200) - **void** - This method does not return a value. #### Response Example None (void return type) ``` -------------------------------- ### Restart(String reason) Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/NativeModuleInterface.md Restarts the React Native application. This method is intended for direct use by developers. It stores an optional reason for the restart and then invokes the internal `loadBundle()` method to perform the actual restart process. Errors are handled internally. ```APIDOC ## Restart(String reason) ### Description Restarts the React Native application with an optional reason. This method is designed for direct invocation by developers. ### Method `Restart` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **reason** (String) - Optional - The reason for the restart. ### Request Example ```javascript NativeModules.RNRestart.Restart("User initiated refresh"); ``` ### Response #### Success Response void #### Response Example None (void return type) ``` -------------------------------- ### restart: (iOS) Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/NativeModuleInterface.md Provides an alternative method name for restarting the React Native application on iOS, following JavaScript naming conventions. It accepts an optional reason string. ```APIDOC ## restart: (iOS) ### Description Restarts the React Native application on iOS, following JavaScript naming conventions. Accepts an optional reason. ### Method Native Module Method (Objective-C) ### Endpoint `RNRestart.restart:(reason)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **reason** (NSString) - Optional - The reason for the restart. ``` -------------------------------- ### Upgrade Package with npm Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Use this command to upgrade the react-native-restart package to the latest version when using npm. ```bash npm update react-native-restart ``` -------------------------------- ### Test Application Restart Functionality Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/USAGE_PATTERNS.md This helper function is designed for end-to-end testing to verify the restart mechanism. It triggers an application restart with a specific prefix for later verification. The app will restart, so subsequent code in this function will not execute. ```typescript import RNRestart from 'react-native-restart'; import { Platform } from 'react-native'; export async function testRestartFunctionality() { try { // Test 1: Call restart RNRestart.restart('e2e_test_restart'); // Note: App will restart, so this won't complete normally // On next startup, we can verify the restart reason } catch (error) { console.error('Restart test failed:', error); } } ``` -------------------------------- ### C++ Error Rejection Messages Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/ERRORS.md These C++ snippets show how promise rejections are formatted for different error conditions on Windows. The first is for foreground or other general failures, while the second provides detailed HRESULT information for asynchronous operation errors. ```cpp // Specific rejection message for foreground/other failures promise.Reject("restart request rejected."); ``` ```cpp // For async operation errors std::stringstream errorCode; errorCode << "0x" << std::hex << action.ErrorCode(); error.Message = "HRESULT " + errorCode.str() + ": " + std::system_category().message(action.ErrorCode()); promise.Reject(error); ``` -------------------------------- ### Developer Menu Restart Options Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/USAGE_PATTERNS.md Provides options in an alert dialog for restarting the app, with or without clearing cache or resetting state, specifically for development builds. This function should be called conditionally within development mode. ```typescript import RNRestart from 'react-native-restart'; import { Alert, Settings } from 'react-native'; function showDeveloperMenu() { const isDevelopmentMode = __DEV__; if (!isDevelopmentMode) { return null; } const options = [ { text: 'Restart App', onPress: () => { RNRestart.restart('developer_restart'); }, }, { text: 'Restart (Clear Cache)', onPress: async () => { await clearAppCache(); RNRestart.restart('developer_restart_clear_cache'); }, }, { text: 'Restart (Reset State)', onPress: async () => { await resetAppState(); RNRestart.restart('developer_restart_reset_state'); }, }, ]; Alert.alert( 'Developer Menu', 'Select an option:', [...options, { text: 'Cancel', style: 'cancel' }] ); } export default showDeveloperMenu; ``` -------------------------------- ### Exported restart Method Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/NativeModuleInterface.md The restart method is an alternative to Restart, offering identical functionality. It is the preferred method for new code implementations. ```java @ReactMethod public void restart(String reason) ``` -------------------------------- ### restart(String reason) Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/NativeModuleInterface.md An alternative method to restart the React Native application, functionally identical to `Restart(String reason)`. It is the preferred method for new implementations. It accepts an optional reason string and triggers the application restart process. ```APIDOC ## restart(String reason) ### Description Restarts the React Native application with an optional reason. This method is functionally identical to `Restart(String reason)` and is the preferred method for new code. ### Method `restart` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **reason** (String) - Optional - The reason for the restart. ### Request Example ```javascript NativeModules.RNRestart.restart("App update available"); ``` ### Response #### Success Response void #### Response Example None (void return type) ``` -------------------------------- ### Android RestartPackage Implementation Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/NativeModuleInterface.md Implements the ReactPackage interface for registering the RestartModule on Android. This class is responsible for creating and returning the native module instance. ```java public class RestartPackage implements ReactPackage { @Override public List createNativeModules(ReactApplicationContext reactContext) { List modules = new ArrayList<>(); modules.add(new RestartModule(reactContext)); return modules; } @Override public List createViewManagers(ReactApplicationContext reactContext) { return new ArrayList<>(); } } ``` -------------------------------- ### Restart Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/AndroidImplementation.md Initiates a restart of the application with an optional reason. This method is called asynchronously from JavaScript and does not wait for the restart to complete. ```APIDOC ## Restart(String reason) ### Description Initiates a restart of the application with an optional reason. This method is called asynchronously from JavaScript and does not wait for the restart to complete. ### Method @ReactMethod ### Parameters #### Path Parameters - **reason** (String) - Optional - Optional reason for the restart ### Return Type void ### Throws No exceptions thrown; all errors handled internally. ``` -------------------------------- ### Upgrade Package with Yarn Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/INSTALLATION_AND_SETUP.md Use this command to upgrade the react-native-restart package to the latest version when using Yarn. ```bash yarn upgrade react-native-restart ``` -------------------------------- ### Exported Restart Method (JavaScript Convention) Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/NativeModuleInterface.md Exports a method named `restart:` which is functionally identical to `Restart:`. This naming convention aligns with JavaScript practices and is the preferred method for triggering restarts from the JavaScript layer. ```objectivec RCT_EXPORT_METHOD(restart: (NSString *)reason) ``` -------------------------------- ### App Restart with Reason Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/USAGE_PATTERNS.md Restarts the application and provides a string reason for the restart. This is helpful for tracking and debugging restart triggers in production or development. ```typescript import RNRestart from 'react-native-restart'; function handleConfigUpdate() { RNRestart.restart('config_update'); } function handleVersionUpdate() { RNRestart.restart('version_update'); } function handleCrashRecovery() { RNRestart.restart('crash_recovery'); } ``` -------------------------------- ### Restart() (Deprecated) Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/api-reference/RNRestart.md Deprecated method that performs the same function as `restart()`. It is included for backward compatibility, but new code should use `restart()` instead. ```APIDOC ## Restart() ### Description Deprecated method that performs the same function as `restart()`. Included for backward compatibility. ### Method `Restart(reason?: string): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **reason** (string) - Optional - Description: Optional reason string describing why the restart was triggered. ### Request Example ```javascript import RNRestart from 'react-native-restart'; // Deprecated usage RNRestart.Restart('legacy_restart'); ``` ### Response #### Success Response (200) - **void** - This method does not return a value. #### Response Example None (void return type) ### Status Deprecated. Use `restart()` instead. ``` -------------------------------- ### Safe Restart with Platform Fallback Source: https://github.com/avishayil/react-native-restart/blob/master/_autodocs/USAGE_PATTERNS.md Safely restarts the application, with a fallback for platforms that might not support the direct restart method. Ensure RNRestart is imported. ```typescript import RNRestart from 'react-native-restart'; import { Platform } from 'react-native'; async function safeRestart(reason: string) { try { if (Platform.OS === 'windows') { await RNRestart.restart(reason); } else { RNRestart.restart(reason); } } catch (error) { console.error('Restart failed:', error); // Fallback: perform manual reset instead await resetAppState(); } } ```