Skip to content

Commit

Permalink
Avoid potential multiple invocations of loginWithRedirect (#311)
Browse files Browse the repository at this point in the history
* Avoid potential multiple invocations of loginWithRedirect

Resolves auth0/auth0-react#309

* add test to assert single call

* remove comment
  • Loading branch information
rahat862 committed Dec 23, 2021
1 parent dc73c75 commit 2739605
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
23 changes: 23 additions & 0 deletions __tests__/with-authentication-required.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -189,4 +189,27 @@ describe('withAuthenticationRequired', () => {
)
);
});

it('should call loginWithRedirect only once even if parent state changes', async () => {
mockClient.getUser.mockResolvedValue(undefined);
const MyComponent = (): JSX.Element => <>Private</>;
const WrappedComponent = withAuthenticationRequired(MyComponent);
const App = ({ foo }: { foo: number }): JSX.Element => (
<div>
{foo}
<Auth0Provider clientId="__test_client_id__" domain="__test_domain__">
<WrappedComponent />
</Auth0Provider>
</div>
);
const { rerender } = render(<App foo={1} />);
await waitFor(() =>
expect(mockClient.loginWithRedirect).toHaveBeenCalled()
);
mockClient.loginWithRedirect.mockClear();
rerender(<App foo={2} />);
await waitFor(() =>
expect(mockClient.loginWithRedirect).not.toHaveBeenCalled()
);
});
});
4 changes: 2 additions & 2 deletions src/with-authentication-required.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ const withAuthenticationRequired = <P extends object>(
const {
returnTo = defaultReturnTo,
onRedirecting = defaultOnRedirecting,
loginOptions = {},
claimCheck = (): boolean => true,
loginOptions,
} = options;

/**
Expand All @@ -101,7 +101,7 @@ const withAuthenticationRequired = <P extends object>(
const opts = {
...loginOptions,
appState: {
...loginOptions.appState,
...(loginOptions && loginOptions.appState),
returnTo: typeof returnTo === 'function' ? returnTo() : returnTo,
},
};
Expand Down

0 comments on commit 2739605

Please sign in to comment.