Skip to content

Commit

Permalink
fix: add error handling capabilities (#4447)
Browse files Browse the repository at this point in the history
  • Loading branch information
adrians5j authored Dec 16, 2024
1 parent 2e18a18 commit 34b5ab0
Showing 1 changed file with 23 additions and 11 deletions.
34 changes: 23 additions & 11 deletions packages/app-page-builder-elements/src/hooks/useLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,22 @@ import { useEffect, useMemo, useState, type DependencyList } from "react";
import { createObjectHash } from "./useLoader/createObjectHash";
import { useRenderer } from "..";

export interface RendererLoader<TData = unknown> {
export interface RendererLoader<TData = unknown, TError = unknown> {
data: TData | null;
loading: boolean;
cacheHit: boolean;
cacheKey: null | string;
error: null | TError;
}

export interface UseLoaderOptions {
cacheKey?: DependencyList;
}

export function useLoader<TData = unknown>(
export function useLoader<TData = unknown, TError = unknown>(
loaderFn: () => Promise<TData>,
options?: UseLoaderOptions
): RendererLoader<TData> {
): RendererLoader<TData, TError> {
const { getElement, loaderCache } = useRenderer();

const element = getElement();
Expand All @@ -29,15 +30,16 @@ export function useLoader<TData = unknown>(
return loaderCache.read<TData>(cacheKey);
}, [cacheKey]);

const [loader, setLoader] = useState<RendererLoader<TData>>(
const [loader, setLoader] = useState<RendererLoader<TData, TError>>(
cachedData
? {
data: cachedData,
loading: false,
cacheHit: true,
cacheKey
cacheKey,
error: null
}
: { data: null, loading: true, cacheHit: false, cacheKey: null }
: { data: null, loading: true, cacheHit: false, cacheKey: null, error: null }
);

useEffect(() => {
Expand All @@ -46,15 +48,25 @@ export function useLoader<TData = unknown>(
}

if (cachedData) {
setLoader({ data: cachedData, loading: false, cacheKey, cacheHit: true });
setLoader({ data: cachedData, loading: false, cacheKey, cacheHit: true, error: null });
return;
}

setLoader({ data: loader.data, loading: true, cacheKey, cacheHit: false });
loaderFn().then(data => {
loaderCache.write(cacheKey, data);
setLoader({ data, loading: false, cacheKey, cacheHit: false });
setLoader({
data: loader.data,
error: loader.error,
loading: true,
cacheKey,
cacheHit: false
});
loaderFn()
.then(data => {
loaderCache.write(cacheKey, data);
setLoader({ data, error: null, loading: false, cacheKey, cacheHit: false });
})
.catch(error => {
setLoader({ data: null, error, loading: false, cacheKey, cacheHit: false });
});
}, [cacheKey]);

return loader;
Expand Down

0 comments on commit 34b5ab0

Please sign in to comment.