@@ -28,35 +28,38 @@ function EditText({ navigation }) {
2828 const [text , setText ] = React .useState (' ' );
2929 const hasUnsavedChanges = Boolean (text);
3030
31- React .useEffect (
32- () =>
33- navigation .addListener (' beforeRemove' , (e ) => {
34- if (! hasUnsavedChanges) {
35- // If we don't have unsaved changes, then we don't need to do anything
36- return ;
37- }
38-
39- // Prevent default behavior of leaving the screen
40- e .preventDefault ();
41-
42- // Prompt the user before leaving the screen
43- Alert .alert (
44- ' Discard changes?' ,
45- ' You have unsaved changes. Are you sure to discard them and leave the screen?' ,
46- [
47- { text: " Don't leave" , style: ' cancel' , onPress : () => {} },
48- {
49- text: ' Discard' ,
50- style: ' destructive' ,
51- // If the user confirmed, then we dispatch the action we blocked earlier
52- // This will continue the action that had triggered the removal of the screen
53- onPress : () => navigation .dispatch (e .data .action ),
54- },
55- ]
56- );
57- }),
58- [navigation, hasUnsavedChanges]
59- );
31+ React .useEffect (() => {
32+ const unsubscribe = navigation .addListener (' beforeRemove' , (e ) => {
33+ if (! hasUnsavedChanges) {
34+ // If we don't have unsaved changes, then we don't need to do anything
35+ return ;
36+ }
37+
38+ // Prevent default behavior of leaving the screen
39+ e .preventDefault ();
40+
41+ // Prompt the user before leaving the screen
42+ Alert .alert (
43+ ' Discard changes?' ,
44+ ' You have unsaved changes. Are you sure to discard them and leave the screen?' ,
45+ [
46+ { text: " Don't leave" , style: ' cancel' , onPress : () => {} },
47+ {
48+ text: ' Discard' ,
49+ style: ' destructive' ,
50+ // If the user confirmed, then we dispatch the action we blocked earlier
51+ // This will continue the action that had triggered the removal of the screen
52+ onPress : () => navigation .dispatch (e .data .action ),
53+ },
54+ ]
55+ );
56+ });
57+
58+ // Unsubscribe the listener when the component unmounts to avoid memory leaks
59+ return () => {
60+ unsubscribe ();
61+ };
62+ }, [navigation, hasUnsavedChanges]);
6063
6164 return (
6265 < TextInput
0 commit comments