What is the role of the reset function in React Query?

376 Views Asked by At

I'm using react-query and react-error-boundary library in my Next.js project. I've noticed that if I use the reset function within the QueryErrorResetBoundary component, it triggers a re-render. However, when I navigate back without using React Query's reset, and instead use resetErrorBoundary as shown in the code below, the fallback screen disappears. Can you explain why this happens?

/ /ErrorBoundaryLayout
function ErrorBoundaryLayout({children}) {
    return (
        <QueryErrorResetBoundary>
            {({ reset }) => (
                <ErrorBoundary
                    // onReset={reset} I added comments
                    fallbackRender={({ error, resetErrorBoundary }) => {
                        return (
                            <ErrorFallback
                                resetErrorBoundary={resetErrorBoundary}
                            />
                        );
                    }}
                >
                  {children}
                </ErrorBoundary>
            )}
        </QueryErrorResetBoundary>
    );
}

//ErrorFallback
unction ErrorFallback({resetErrorBoundary}) {
    const router = useRouter();
   
    // this doesn't work
    const navigateToBack = () => {
        resetErrorBoundary();
        router.back();
    };

    // this way works
    const errorLocation = useRef(router.asPath);
    useEffect(() => {
        if (errorLocation.current !== router.asPath) {
         resetErrorBoundary();
        }
    }, [router.asPath]);

    return (
                <Button onClick={router.back}/>
    );
}
1

There are 1 best solutions below

0
TkDodo On

reset from the QueryErrorResetBoundary makes sure that the Query will re-fetch when it is mounted the next time. The flow is:

  • query fetches, fails
  • query throws error to the nearest error boundary, then stops fetches until reset is called.
  • error boundary shows fallback content
  • user clicks a button, which will:
    • reset the boundary itself with resetErrorBoundary, which will unmount the boundary and show the component again
    • reset the Query with reset so that it can fetch again.
  • then, the component mounts again, and you should see a loading spinner ...