mikecousins/react-pdf-js

Handle an empty source file

Closed this issue · 3 comments

How can I handle the empty source file? According to the Rules of Hooks there is no way to call usePdf hook conditionally. Sure I can wrap the component using the usePdf hook but in that case I need to use e.g. two different components for loading state or am I missing sth?

Basically my question is how can I display a loading bar while the file is not ready to be rendered?

I might be misreading your initial comment, but what I'm doing is utilizing loading that gets returned from usePdf and conditionally showing the PDF or a loading indicator conditionally based on that.

export const PdfViewer = ({ file }) => {
    const [page, setPage] = useState(1);
    const [pages, setPages] = useState(null);
    const canvasEl = useRef(null);

    const [loading, numPages] = usePdf({
        file,
        page,
        canvasEl
    });

    useEffect(() => {
        setPages(numPages);
    }, [numPages]);

    return !loading ? (
        <canvas ref={canvasEl} />
    ) : (
        <div>Loading...</div>
    )
}

But there's another issue with handling an empty source file:

if there is no file then there's no way to handle that empty file. I'm using usePdf with the code implementation above and users will end up seeing a loading indicator instead of some error component. Is there any way to handle errors with like an onError prop or an option to pass in an error component to show when the file is empty or fails to load?

I'd split the component up so that you're using it only when you have a file ready to go. You can also use the Pdf component instead of the hook if you want.

Thanks! Splitting the component up definitely helps. I also didn't realize there was a Pdf component. I'm just noticing it now after reading the source code 😅