Skip to content
Merged
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
35 changes: 23 additions & 12 deletions examples/base/src/Content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ import { useAuthClient } from './auth';
export const Content: React.FC = () => {
const authClient = useAuthClient();

const [doLogin, isLoginLoading] = useAsyncCallback(() => authClient.login(), [
const [doLogin, isLoginLoading, loginError] = useAsyncCallback(() => authClient.login(), [
authClient,
]);
const [doRefresh, isRefreshLoading] = useAsyncCallback(
const [doRefresh, isRefreshLoading, refreshError] = useAsyncCallback(
() => authClient.refresh(),
[authClient]
);
const [doLogout, isLogoutLoading] = useAsyncCallback(
const [doLogout, isLogoutLoading, logoutError] = useAsyncCallback(
() => authClient.logout(),
[authClient]
);
Expand Down Expand Up @@ -49,25 +49,36 @@ export const Content: React.FC = () => {
{isLoginLoading ? <p>Login in progress..</p> : null}
{isRefreshLoading ? <p>Refresh in progress..</p> : null}

{loginError != null ? <p role="alert">Login error: {loginError instanceof Error ? loginError.message : 'An error occurred'}</p> : null}
{refreshError != null ? <p role="alert">Refresh error: {refreshError instanceof Error ? refreshError.message : 'An error occurred'}</p> : null}
{logoutError != null ? <p role="alert">Logout error: {logoutError instanceof Error ? logoutError.message : 'An error occurred'}</p> : null}

<p>Tokens:</p>
<pre>{JSON.stringify(authClient.tokens, null, 2)}</pre>
</div>
);
};

type AsyncCallbackState = { isLoading: boolean; error: unknown };

function useAsyncCallback<T extends (...args: never[]) => Promise<unknown>>(
callback: T,
deps: DependencyList
): [T, boolean] {
const [isLoading, setLoading] = useState(false);
const cb = useCallback(async (...argsx: never[]) => {
setLoading(true);
): [(...args: Parameters<T>) => Promise<unknown>, boolean, unknown] {
const [{ isLoading, error }, setState] = useState<AsyncCallbackState>({
isLoading: false,
error: null,
});
const cb = useCallback(async (...argsx: Parameters<T>) => {
setState({ isLoading: true, error: null });
try {
return await callback(...argsx);
} finally {
setLoading(false);
const result = await callback(...argsx);
setState({ isLoading: false, error: null });
return result;
} catch (err) {
setState({ isLoading: false, error: err });
}
}, deps) as T;
}, deps);

return [cb, isLoading];
return [cb, isLoading, error];
}
Loading