Skip to content

Commit

Permalink
fix: removal of non-existing listener should not break updating ref (#…
Browse files Browse the repository at this point in the history
…10067)

Calling `removeListener` on event that doesn't have any listeners will add new key for that event to listeners with value `undefined`. After that attempts to set `ref.current` will fail with "Cannot read property 'forEach' of undefined" error. Fix is quite simple. Just needed to add check if there is listeners for the given event.

FYI @satya164. This is related to your recent change acdde18
  • Loading branch information
split authored and satya164 committed Nov 27, 2022
1 parent 440ec07 commit 769a060
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,11 @@ it('adds the listener even if container is mounted later', () => {

expect(listener).toHaveBeenCalledTimes(1);
});

it('removal of non-existing listener should not break updating ref', () => {
const ref = createNavigationContainerRef<ParamListBase>();
ref.removeListener('state', jest.fn());
expect(() => {
ref.current = createNavigationContainerRef<ParamListBase>();
}).not.toThrow();
});
4 changes: 3 additions & 1 deletion packages/core/src/createNavigationContainerRef.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ export default function createNavigationContainerRef<
event: string,
callback: (...args: any[]) => void
) => {
listeners[event] = listeners[event]?.filter((cb) => cb !== callback);
if (listeners[event]) {
listeners[event] = listeners[event].filter((cb) => cb !== callback);
}
};

let current: NavigationContainerRef<ParamList> | null = null;
Expand Down

0 comments on commit 769a060

Please sign in to comment.