mirror of
https://github.com/DefectingCat/DefectingCat.github.io
synced 2025-07-16 01:01:38 +00:00
Add router loading
This commit is contained in:
36
lib/hooks/useRouteLoading.ts
Normal file
36
lib/hooks/useRouteLoading.ts
Normal 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;
|
@ -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;
|
||||
|
@ -1,5 +1,6 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"target": "es5",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
|
Reference in New Issue
Block a user