Skip to content

Commit

Permalink
feat: add support for the onError callback in useAsset
Browse files Browse the repository at this point in the history
  • Loading branch information
trezy committed Jul 17, 2024
1 parent 62dd2ea commit 7fdb11c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
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;

0 comments on commit 7fdb11c

Please sign in to comment.