|
| 1 | +import { DefaultTheme } from '@react-navigation/native'; |
| 2 | +import * as React from 'react'; |
| 3 | +// eslint-disable-next-line no-restricted-imports |
| 4 | +import { Pressable, StyleSheet, Text, View } from 'react-native'; |
| 5 | + |
| 6 | +export class ErrorBoundary extends React.Component< |
| 7 | + { |
| 8 | + children: React.ReactNode; |
| 9 | + onError?: (error: Error, info: React.ErrorInfo) => void; |
| 10 | + }, |
| 11 | + { error: Error | null } |
| 12 | +> { |
| 13 | + static getDerivedStateFromError(error: Error) { |
| 14 | + return { error }; |
| 15 | + } |
| 16 | + |
| 17 | + state: { error: Error | null } = { error: null }; |
| 18 | + |
| 19 | + componentDidCatch(error: Error, info: React.ErrorInfo) { |
| 20 | + this.props.onError?.(error, info); |
| 21 | + } |
| 22 | + |
| 23 | + render() { |
| 24 | + const { error } = this.state; |
| 25 | + |
| 26 | + if (error) { |
| 27 | + return ( |
| 28 | + <View style={styles.container}> |
| 29 | + <Text style={styles.errorText}>{error.message}</Text> |
| 30 | + <Pressable |
| 31 | + style={styles.button} |
| 32 | + onPress={() => { |
| 33 | + this.setState({ error: null }); |
| 34 | + }} |
| 35 | + > |
| 36 | + <Text style={styles.buttonText}>Try Again</Text> |
| 37 | + </Pressable> |
| 38 | + </View> |
| 39 | + ); |
| 40 | + } |
| 41 | + |
| 42 | + return this.props.children; |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +const styles = StyleSheet.create({ |
| 47 | + container: { |
| 48 | + flex: 1, |
| 49 | + justifyContent: 'center', |
| 50 | + alignItems: 'center', |
| 51 | + padding: 16, |
| 52 | + }, |
| 53 | + errorText: { |
| 54 | + ...DefaultTheme.fonts.heavy, |
| 55 | + color: DefaultTheme.colors.notification, |
| 56 | + fontSize: 16, |
| 57 | + }, |
| 58 | + button: { |
| 59 | + marginTop: 8, |
| 60 | + padding: 16, |
| 61 | + }, |
| 62 | + buttonText: { |
| 63 | + ...DefaultTheme.fonts.medium, |
| 64 | + color: DefaultTheme.colors.primary, |
| 65 | + }, |
| 66 | +}); |
0 commit comments