Skip to content

Commit

Permalink
feat: Support expo-router focus events
Browse files Browse the repository at this point in the history
  • Loading branch information
ntucker committed May 1, 2024
1 parent 6e9d36b commit 7d3cd45
Show file tree
Hide file tree
Showing 3 changed files with 802 additions and 25 deletions.
5 changes: 5 additions & 0 deletions packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@
"peerDependencies": {
"@react-navigation/native": "^6.0.0",
"@types/react": "^16.8.4 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"expo-router": "^3.0.0",
"react": "^16.8.4 || ^17.0.0 || ^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
Expand All @@ -141,13 +142,17 @@
},
"@types/react": {
"optional": true
},
"expo-router": {
"optional": true
}
},
"devDependencies": {
"@anansi/browserslist-config": "^1.4.2",
"@react-navigation/native": "^6.1.6",
"@types/node": "^20.0.0",
"@types/react": "^18.0.30",
"expo-router": "^3.4.8",
"react-native": "^0.74.0"
}
}
31 changes: 23 additions & 8 deletions packages/react/src/hooks/useFocusEffect.native.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,40 @@
import type { useNavigation, NavigationProp } from '@react-navigation/native';
import {
type DependencyList,
type EffectCallback,
useEffect,
useRef,
} from 'react';

const fakeNavigation = { addListener(name: string) {} } as any;
let _useNavigation: typeof useNavigation = () => fakeNavigation;
import('@react-navigation/native')
.then(rn => {
_useNavigation = rn.useNavigation;
const fakeNavigation = {
addListener(name: string, cb: () => void) {
return () => {};
},
};
let _useNavigation = () => fakeNavigation;

console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
// if they are using expo-router they are more likely wanting to use that implementation
// as react-navigation can often appear in node_modules when not used
import('expo-router')
.then(router => {
_useNavigation = router.useNavigation;
console.log('hi', _useNavigation, router);

Check warning on line 21 in packages/react/src/hooks/useFocusEffect.native.ts

View check run for this annotation

Codecov / codecov/patch

packages/react/src/hooks/useFocusEffect.native.ts#L20-L21

Added lines #L20 - L21 were not covered by tests
})
.catch(() => {});
.catch(e => {
console.log('caught error', e);
import('@react-navigation/native')
.then(rn => {
_useNavigation = rn.useNavigation;
})
.catch(() => {});
});

function useFocusEffect(
effect: EffectCallback,
deps?: DependencyList,
runOnMount = false,
) {
let navigation: NavigationProp<ReactNavigation.RootParamList>;
let navigation: typeof fakeNavigation;
// if we aren't in react-navigation context, just ignore focus events
try {
navigation = _useNavigation();
Expand Down
Loading

0 comments on commit 7d3cd45

Please sign in to comment.