Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support expo-router focus events #2999

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions app.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
plugins: ['expo-router'],
platforms: ['android'],
};
3 changes: 2 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ const projects = [
testEnvironment:
'<rootDir>/node_modules/react-native/jest/react-native-env.js',
transformIgnorePatterns: [
'node_modules\\/(?!(((jest-)?react-native)|@react-native(-community)?|react-navigation))', //from RN preset
//from RN preset
'node_modules/(?!((jest-)?react-native|@react-native(-community)?)|react-navigation|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|react-native-svg)',
'<rootDir>/.*__tests__/[^/]+\\.(web|node)\\.(j|t)sx?$',
'<rootDir>/scripts',
],
Expand Down
7 changes: 7 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
"@js-temporal/polyfill": "^0.4.4",
"@react-navigation/native": "^6.0.13",
"@react-navigation/native-stack": "^6.9.1",
"@testing-library/jest-native": "^5.4.3",
"@testing-library/react": "15.0.5",
"@testing-library/react-hooks": "8.0.1",
"@testing-library/react-native": "12.4.5",
Expand All @@ -84,6 +85,11 @@
"eslint-plugin-prettier": "5.1.3",
"eslint-plugin-react": "7.34.1",
"eslint-plugin-react-hooks": "4.6.1",
"expo": "50.0.17",
"expo-constants": "^15.4.6",
"expo-linking": "6.2.2",
"expo-modules-core": "1.11.13",
"expo-status-bar": "1.11.1",
"ignore-styles": "^5.0.1",
"jest": "29.7.0",
"jest-environment-jsdom": "29.7.0",
Expand All @@ -95,6 +101,7 @@
"react": "18.3.1",
"react-dom": "18.3.1",
"react-native": "0.74.0",
"react-native-reanimated": "^3.10.0",
"react-native-safe-area-context": "^4.4.1",
"react-native-screens": "^3.18.2",
"react-test-renderer": "18.3.1",
Expand Down
15 changes: 14 additions & 1 deletion 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,25 @@
},
"@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",
"react-native": "^0.74.0"
"expo": ">=51.0.0-0 <52.0.0",
"expo-constants": "~15.4.6",
"expo-linking": "~6.2.2",
"expo-router": "~3.4.10",
"expo-status-bar": "~1.11.1",
"jest": "^29.7.0",
"jest-expo": "^50.0.4",
"react-native": "^0.74.0",
"react-native-safe-area-context": "4.8.2",
"react-native-screens": "~3.29.0"
}
}
9 changes: 9 additions & 0 deletions packages/react/src/hooks/__tests__/expo-fixtures/_layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { View, Text } from 'react-native';

export default function Layout() {
return (
<View>
<Text>Auth Layout</Text>
</View>
);
}
220 changes: 220 additions & 0 deletions packages/react/src/hooks/__tests__/useSuspense.expo.native.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
import {
State,
initialState,
Controller,
ActionTypes,
actionTypes,
} from '@data-client/core';
import { FetchAction } from '@data-client/core';
import { Endpoint, FetchFunction, ReadEndpoint } from '@data-client/endpoint';
import { normalize } from '@data-client/normalizr';
import { makeRenderDataClient, mockInitialState } from '@data-client/test';
import { jest } from '@jest/globals';
import {
CoolerArticleResource,
InvalidIfStaleArticleResource,
GetNoEntities,
ArticleTimedResource,
ContextAuthdArticleResource,
AuthContext,
PaginatedArticleResource,
CoolerArticle,
PaginatedArticle,
FutureArticleResource,
ArticleTimed,
} from '__tests__/new';
import { createEntityMeta } from '__tests__/utils';
import { Slot } from 'expo-router';
import { ReactComponent } from 'expo-router/build/testing-library/context-stubs';
import { renderRouter, screen, act } from 'expo-router/testing-library';
import { SpyInstance } from 'jest-mock';
import nock from 'nock';
import React, { Suspense } from 'react';
import { Text, View } from 'react-native';
import { InteractionManager } from 'react-native';

// relative imports to avoid circular dependency in tsconfig references
import {
CacheProvider,
useController,
ControllerContext,
StateContext,
AsyncBoundary,
} from '../..';
import { articlesPages, payload, users, nested } from '../test-fixtures';
import useSuspense from '../useSuspense';

function ArticleComponentTester() {
const invalidIfStale = false,
schema = true;
let endpoint =
invalidIfStale ?
InvalidIfStaleArticleResource.get
: CoolerArticleResource.get;
if (!schema) {
endpoint = (endpoint as any).extend({ schema: undefined }) as any;
}
const article = useSuspense(endpoint, {
id: payload.id,
});
return (
<View testID="article">
<Text>{article.title}</Text>
<Text>{article.content}</Text>
</View>
);
}

describe('useSuspense()', () => {
let renderDataClient: ReturnType<typeof makeRenderDataClient>;
const fbmock = jest.fn();

async function testMalformedResponse(
payload: any,
endpoint: ReadEndpoint<FetchFunction, any> = CoolerArticleResource.get,
) {
nock(/.*/)
.persist()
.defaultReplyHeaders({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Content-Type': 'application/json',
})
.get(`/article-cooler/400`)
.reply(200, payload);

const { result, waitForNextUpdate } = renderDataClient(() => {
return useSuspense(endpoint, {
id: 400,
});
});
expect(result.current).toBeUndefined();
await waitForNextUpdate();
expect(result.error).toBeDefined();
expect((result.error as any).status).toBeGreaterThan(399);
expect(result.error).toMatchSnapshot();
}

function Fallback() {
fbmock();
return null;
}

beforeAll(() => {
nock(/.*/)
.persist()
.defaultReplyHeaders({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Access-Token',
'Content-Type': 'application/json',
})
.options(/.*/)
.reply(200)
.get(`/article-cooler/${payload.id}`)
.reply(200, payload)
.get(`/article-time/${payload.id}`)
.reply(200, { ...payload, createdAt: '2020-06-07T02:00:15+0000' })
.delete(`/article-cooler/${payload.id}`)
.reply(204, '')
.delete(`/article/${payload.id}`)
.reply(200, {})
.get(`/article-cooler/0`)
.reply(403, {})
.get(`/article-cooler/666`)
.reply(200, '')
.get(`/article-cooler`)
.reply(200, nested)
.get(`/user`)
.reply(200, users);
});

afterAll(() => {
nock.cleanAll();
});

beforeEach(() => {
renderDataClient = makeRenderDataClient(CacheProvider);
fbmock.mockReset();
});

afterEach(() => {
try {
screen.unmount();
// eslint-disable-next-line no-empty
} catch (e) {}
});

describe('result is stale and options.invalidIfStale is false', () => {
const { entities, result } = normalize(payload, CoolerArticle);
const fetchKey = CoolerArticleResource.get.key({ id: payload.id });
const state = {
...initialState,
entities,
entityMeta: createEntityMeta(entities),
results: {
[fetchKey]: result,
},
meta: {
[fetchKey]: {
date: 0,
expiresAt: 0,
},
},
};
let thenavigation: any;
function Home() {
return <Text>Home</Text>;
}

const dispatch = jest.fn(() => Promise.resolve());
const controller = new Controller({ dispatch });
// const Stack = createNativeStackNavigator();

function Layout() {
return (
<StateContext.Provider value={state}>
<ControllerContext.Provider value={controller}>
<AsyncBoundary fallback={<Fallback />}>
<Slot />
</AsyncBoundary>
</ControllerContext.Provider>
</StateContext.Provider>
);
}
it('should fetch expo route changes and results are stale', async () => {
dispatch.mockClear();

const { getByText, getByTestId } = renderRouter(
{
_layout: Layout,
index: Home,
article: ArticleComponentTester,
},
{
initialUrl: '/article',
},
);

// expect(fbmock).not.toBeCalled();
// await new Promise(resolve =>
// InteractionManager.runAfterInteractions(() => {
// resolve(null);
// }),
// );
// // still should revalidate
// expect(dispatch.mock.calls.length).toBe(1);
// act(() => thenavigation.navigate('Home'));
// expect(getByText('Home')).toBeDefined();

// act(() => thenavigation.goBack());
// await new Promise(resolve =>
// InteractionManager.runAfterInteractions(() => {
// resolve(null);
// }),
// );
// expect(getByTestId('article')).toBeDefined();
// // since we got focus back we should have called again
// expect(dispatch.mock.calls.length).toBe(2);
});
});
});
8 changes: 5 additions & 3 deletions packages/react/src/hooks/__tests__/useSuspense.native.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,8 @@ describe('useSuspense()', () => {
});
});

});

it('should NOT suspend if result is not stale and options.invalidIfStale is true', () => {
const { entities, result } = normalize(payload, CoolerArticle);
const fetchKey = InvalidIfStaleArticleResource.get.key({ id: payload.id });
Expand Down Expand Up @@ -473,19 +475,19 @@ describe('useSuspense()', () => {
});*/
});

/*it('should not suspend with null params to useSuspense()', () => {
it('should not suspend with null params to useSuspense()', () => {
let article: CoolerArticle | undefined;
const { result } = renderDataClient(() => {
const a = useSuspense(CoolerArticleResource.get, null);
a.tags;
a?.tags;
article = a;
// @ts-expect-error
const b: CoolerArticleResource = a;
return 'done';
});
expect(result.current).toBe('done');
expect(article).toBeUndefined();
});*/
});

it('should maintain schema structure even with null params', () => {
let articles: PaginatedArticle[] | undefined;
Expand Down
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);
})
.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
Loading