Skip to content
This repository has been archived by the owner on Feb 8, 2020. It is now read-only.

Commit

Permalink
fix: don't throw when switching navigator. fixes #91
Browse files Browse the repository at this point in the history
  • Loading branch information
satya164 committed Oct 3, 2019
1 parent a8851b7 commit 19be2b4
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
17 changes: 11 additions & 6 deletions packages/core/src/EnsureSingleNavigator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,30 @@ export const SingleNavigatorContext = React.createContext<
* Component which ensures that there's only one navigator nested under it.
*/
export default function EnsureSingleNavigator({ children }: Props) {
const [currentKey, setCurrentKey] = React.useState<string | undefined>();
const navigatorKeyRef = React.useRef<string | undefined>();

const value = React.useMemo(
() => ({
register(key: string) {
const currentKey = navigatorKeyRef.current;

if (currentKey !== undefined && key !== currentKey) {
throw new Error(MULTIPLE_NAVIGATOR_ERROR);
}

setCurrentKey(key);
navigatorKeyRef.current = key;
},
unregister(key: string) {
if (currentKey !== undefined && key !== currentKey) {
throw new Error(MULTIPLE_NAVIGATOR_ERROR);
const currentKey = navigatorKeyRef.current;

if (key !== currentKey) {
return;
}

setCurrentKey(undefined);
navigatorKeyRef.current = undefined;
},
}),
[currentKey]
[]
);

return (
Expand Down
27 changes: 27 additions & 0 deletions packages/core/src/__tests__/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -695,3 +695,30 @@ it('throws when multiple screens with same name are defined', () => {
"A navigator cannot contain multiple 'Screen' components with the same name (found duplicate screen named 'foo')"
);
});

it('switches rendered navigators', () => {
const TestNavigator = (props: any) => {
useNavigationBuilder(MockRouter, props);
return null;
};

const root = render(
<NavigationContainer>
<TestNavigator key="a">
<Screen name="foo" component={jest.fn()} />
</TestNavigator>
</NavigationContainer>
);

expect(() =>
root.update(
<NavigationContainer>
<TestNavigator key="b">
<Screen name="foo" component={jest.fn()} />
</TestNavigator>
</NavigationContainer>
)
).not.toThrowError(
'Another navigator is already registered for this container.'
);
});

0 comments on commit 19be2b4

Please sign in to comment.