Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add onError callback to useAsset #504

Merged
merged 12 commits into from
Aug 1, 2024
19 changes: 18 additions & 1 deletion src/hooks/useAsset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type {
} from 'pixi.js';
import type { AssetRetryOptions } from '../typedefs/AssetRetryOptions.ts';
import type { AssetRetryState } from '../typedefs/AssetRetryState.ts';
import type { ErrorCallback } from '../typedefs/ErrorCallback.ts';

const errorCache: Map<UnresolvedAsset | string, AssetRetryState> = new Map();

Expand All @@ -19,10 +20,19 @@ export function useAsset<T>(
options: (UnresolvedAsset<T> & AssetRetryOptions) | string,
/** @description A function to be called when the asset loader reports loading progress. */
onProgress: ProgressCallback,
/** @description A function to be called when the asset loader reports loading progress. */
onError?: ErrorCallback,
)
{
if (typeof window === 'undefined')
{
/**
* This is a weird hack that allows us to throw the error during
* serverside rendering, but still causes it to be handled appropriately
* in Next.js applications.
*
* @see https://github.com/vercel/next.js/blob/38b3423160afc572ad933c24c86fc572c584e70b/packages/next/src/shared/lib/lazy-dynamic/bailout-to-csr.ts
*/
throw Object.assign(Error('`useAsset` will only run on the client.'), {
digest: 'BAILOUT_TO_CLIENT_SIDE_RENDERING',
});
Expand All @@ -42,7 +52,14 @@ export function useAsset<T>(
// Rethrow the cached error if we are not retrying on failure or have reached the max retries
if (state && (!retryOnFailure || state.retries > maxRetries))
{
throw state.error;
if (typeof onError === 'function')
{
onError?.(state.error);
}
else
{
throw state.error;
}
}

throw Assets
Expand Down
1 change: 1 addition & 0 deletions src/typedefs/ErrorCallback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type ErrorCallback = (error: Error) => void;
Loading