Created
May 4, 2025 08:22
-
-
Save MonaAghili/232a1d2edf0c3e23b40a2c7369d78c03 to your computer and use it in GitHub Desktop.
Revisions
-
MonaAghili created this gist
May 4, 2025 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,94 @@ I created this boundery for my react native app is it a good solution or is there another solution? i use it as a provider for global error handeling can you refactor it? import React, { createContext, ReactNode, useContext, useState } from 'react'; import { StyleSheet, Text, TouchableOpacity, View } from 'react-native'; const ErrorContext = createContext<ErrorContextType | undefined>(undefined); interface ErrorContextType { error: Error | null; setError: (error: Error | null) => void; resetError: () => void; } export function ErrorProvider({ children }: { children: ReactNode }) { const [error, setError] = useState<Error | null>(null); const resetError = () => setError(null); const contextValue: ErrorContextType = { error, setError, resetError, }; // Render fallback UI or children if (error) { return ( <View style={styles.container}> <Text style={styles.title}>Something went wrong</Text> <Text style={styles.message}>{error.message || 'an unexpected error occurred'}</Text> <TouchableOpacity style={styles.button} onPress={resetError}> <Text style={styles.buttonText}>Try Again</Text> </TouchableOpacity> </View> ); } return <ErrorContext.Provider value={contextValue}>{children}</ErrorContext.Provider>; } // Custom hook to use the error context export function useError() { const context = useContext(ErrorContext); if (context === undefined) { throw new Error('useError must be used within an ErrorProvider'); } return context; } // a higher order component for try catch pattern export function withErrorHandling<P extends object>(Component: React.ComponentType<P>) { return function WithErrorHandling(props: P) { const { setError } = useError(); try { return <Component {...props} />; } catch (error) { setError(error instanceof Error ? error : new Error('An unknown error occurred')); return null; } }; } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20, backgroundColor: '#fff', }, title: { fontSize: 18, fontWeight: 'bold', marginBottom: 12, }, message: { fontSize: 14, color: '#666', textAlign: 'center', marginBottom: 20, }, button: { backgroundColor: '#2196F3', paddingVertical: 10, paddingHorizontal: 20, borderRadius: 4, }, buttonText: { color: 'white', fontWeight: 'bold', }, });