Skip to content

Commit

Permalink
add error state for PDFReader
Browse files Browse the repository at this point in the history
  • Loading branch information
jackiequach committed Jun 27, 2024
1 parent ff0a1ed commit 17bf9b8
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
15 changes: 14 additions & 1 deletion src/PdfReader/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,8 @@ export default function usePdfReader(args: ReaderArguments): ReaderReturn {
};
}

if (state.state === 'ERROR') throw state.loadError;

// if (isFetching) {
// // The Reader is fetching a PDF resource
// return {
Expand Down Expand Up @@ -283,6 +285,13 @@ export default function usePdfReader(args: ReaderArguments): ReaderReturn {
});
};

const onDocumentLoadError = (error: Error) => {
dispatch({
type: 'PDF_LOAD_ERROR',
error: error,
});
};

function onRenderSuccess(page: PageProps) {
if (!page.height || !page.width)
throw new Error(
Expand Down Expand Up @@ -331,7 +340,11 @@ export default function usePdfReader(args: ReaderArguments): ReaderReturn {
}
`}
</style>
<Document file={state.resource} onLoadSuccess={onDocumentLoadSuccess}>
<Document
file={state.resource}
onLoadSuccess={onDocumentLoadSuccess}
onLoadError={onDocumentLoadError}
>
{isParsed && state.numPages && (
<>
{state.settings.isScrolling &&
Expand Down
8 changes: 8 additions & 0 deletions src/PdfReader/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,14 @@ export function makePdfReducer(
state.pageNumber === -1 ? action.numPages : state.pageNumber,
};

case 'PDF_LOAD_ERROR':
return {
...state,
state: 'ERROR',
loadError: action.error,
settings: DEFAULT_SETTINGS,
};

case 'SET_SCROLL':
if (state.state !== 'ACTIVE') {
return handleInvalidTransition(state, action);
Expand Down
10 changes: 9 additions & 1 deletion src/PdfReader/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,14 @@ export type InactiveState = ReaderState &
export type ActiveState = ReaderState &
InternalState & { state: 'ACTIVE'; settings: ReaderSettings };

export type PdfState = InactiveState | ActiveState;
export type ErrorState = ReaderState &
InternalState & {
state: 'ERROR';
loadError: Error;
settings: ReaderSettings;
};

export type PdfState = InactiveState | ActiveState | ErrorState;

export type PdfReaderAction =
| {
Expand All @@ -34,6 +41,7 @@ export type PdfReaderAction =
| { type: 'GO_TO_HREF'; href: string }
| { type: 'RESOURCE_FETCH_SUCCESS'; resource: { data: Uint8Array } }
| { type: 'PDF_PARSED'; numPages: number }
| { type: 'PDF_LOAD_ERROR'; error: Error }
| { type: 'SET_SCALE'; scale: number }
| { type: 'SET_SCROLL'; isScrolling: boolean }
| { type: 'PAGE_LOAD_SUCCESS'; height: number; width: number }
Expand Down

0 comments on commit 17bf9b8

Please sign in to comment.