Add router loading

This commit is contained in:
DefectingCat
2022-01-14 10:23:30 +08:00
parent 7d1ed6d80d
commit 429fcf3d79
3 changed files with 56 additions and 5 deletions

View File

@ -0,0 +1,36 @@
import { useCallback, useEffect, useState } from 'react';
import { useRouter } from 'next/router';
const useRouterLoading = () => {
const router = useRouter();
const [loading, setLoading] = useState(false);
const handleStart = useCallback(
(url: string) => {
url !== router.pathname ? setLoading(true) : setLoading(false);
},
[router.pathname]
);
const handleComplete = useCallback(() => {
setLoading(false);
}, []);
useEffect(() => {
router.events.on('routeChangeStart', handleStart);
router.events.on('routeChangeComplete', handleComplete);
router.events.on('routeChangeError', handleComplete);
// If the component is unmounted, unsubscribe
// from the event with the `off` method:
return () => {
router.events.off('routeChangeStart', handleStart);
router.events.off('routeChangeComplete', handleComplete);
router.events.off('routeChangeError', handleComplete);
};
}, [handleComplete, handleStart, router.events]);
return [loading];
};
export default useRouterLoading;

View File

@ -1,8 +1,22 @@
import '../styles/globals.css'
import type { AppProps } from 'next/app'
import '../styles/globals.css';
import type { AppProps } from 'next/app';
import { NextPage } from 'next';
import { ReactElement, ReactNode } from 'react';
import useRouterLoading from 'lib/hooks/useRouteLoading';
function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
type NextPageWithLayout = NextPage & {
// eslint-disable-next-line no-unused-vars
getLayout?: (page: ReactElement) => ReactNode;
};
type AppPropsWithLayout = AppProps & {
Component: NextPageWithLayout;
};
function MyApp({ Component, pageProps }: AppPropsWithLayout) {
const getLayout = Component.getLayout ?? ((page) => page);
const [loading] = useRouterLoading();
return <>{getLayout(<Component {...pageProps} />)}</>;
}
export default MyApp
export default MyApp;

View File

@ -1,5 +1,6 @@
{
"compilerOptions": {
"baseUrl": ".",
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,