Skip to content

Commit 64dc75c

Browse files
committed
chore: add error boundary to the example app
1 parent 13e3ced commit 64dc75c

File tree

2 files changed

+76
-3
lines changed

2 files changed

+76
-3
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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+
});

example/src/index.tsx

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ import {
5151
} from './screens';
5252
import { NotFound } from './Screens/NotFound';
5353
import { Divider } from './Shared/Divider';
54+
import { ErrorBoundary } from './Shared/ErrorBoundary';
5455
import { ListItem } from './Shared/LIstItem';
5556
import { SettingsItem } from './Shared/SettingsItem';
5657

@@ -351,9 +352,15 @@ export function App() {
351352

352353
const Providers = ({ children }: { children: React.ReactNode }) => {
353354
return (
354-
<ActionSheetProvider>
355-
<>{children}</>
356-
</ActionSheetProvider>
355+
<ErrorBoundary
356+
onError={() => {
357+
AsyncStorage.removeItem(NAVIGATION_PERSISTENCE_KEY);
358+
}}
359+
>
360+
<ActionSheetProvider>
361+
<>{children}</>
362+
</ActionSheetProvider>
363+
</ErrorBoundary>
357364
);
358365
};
359366

0 commit comments

Comments
 (0)