Skip to content
This repository has been archived by the owner on Dec 3, 2022. It is now read-only.

Fix useNavigation params typing #50

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
7 changes: 5 additions & 2 deletions src/Hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ import {
EventType,
} from 'react-navigation';

export function useNavigation<S>(): NavigationScreenProp<S & NavigationRoute> {
export function useNavigation<S, P = NavigationParams>(): NavigationScreenProp<
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good for the specific usecase of params, but for #42 we should also probably remove the hardcoded "NavigationScreenProp" reference because it won't expose the custom navigator actions (like popToTop etc)

I prefer to have one PR fix both the params usecase and custom navigator actions usecases, because if we release a fix for #42 later, we're probably going to break the TS types retrocompatibility so it's likely to be annoying for the users.

S & NavigationRoute,
P
> {
const navigation = useContext(NavigationContext) as any; // TODO typing?
if (!navigation) {
throw new Error(
Expand All @@ -32,7 +35,7 @@ export function useNavigation<S>(): NavigationScreenProp<S & NavigationRoute> {
export function useNavigationParam<T extends keyof NavigationParams>(
paramName: T
) {
return useNavigation().getParam(paramName);
return useNavigation().getParam(paramName); // TODO typing ?
}

export function useNavigationState() {
Expand Down
12 changes: 9 additions & 3 deletions src/__tests__/Hooks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,23 @@ import {

interface DetailsScreenParams {
from: string;
id: number;
}

const HomeScreen = () => {
const { navigate } = useNavigation();
const params: DetailsScreenParams = { from: 'Home' };
const params: DetailsScreenParams = { from: 'Home', id: 1 };
return navigate('Details', params);
};

const DetailsScreen = () => {
const from = useNavigationParam('from');
return <p>{from}</p>;
const id = useNavigation<unknown, DetailsScreenParams>().getParam('id');
return (
<p>
{from}:{id}
</p>
);
};

const OtherScreen = () => {
Expand Down Expand Up @@ -102,7 +108,7 @@ describe('AppNavigator1 Stack', () => {

it('useNavigationParam: Get passed parameter', () => {
const children = navigationContainer.toJSON().children;
expect(children).toContain('Home');
expect(children).toStrictEqual(['Home', ':', '1']);
});

afterEach(() => {
Expand Down