Browse Source
* add loading indicator to sidebar links * fix clicking on same route whould show indicator * maybe final? * handle routeChangeError as well as cleaning up timeout * clearing timeout before creating one instead of routeChangeError * rm unused * add license header * Update usePendingRoute.ts Co-authored-by: dan <dan.abramov@gmail.com>main
Yousef M. El-Gohary
3 years ago
committed by
GitHub
3 changed files with 51 additions and 1 deletions
@ -0,0 +1,41 @@ |
|||
/* |
|||
* Copyright (c) Facebook, Inc. and its affiliates. |
|||
*/ |
|||
|
|||
import {useRouter} from 'next/router'; |
|||
import React from 'react'; |
|||
|
|||
const usePendingRoute = () => { |
|||
const {events} = useRouter(); |
|||
const [pendingRoute, setPendingRoute] = React.useState<string | null>(null); |
|||
const currentRoute = React.useRef<string | null>(null); |
|||
React.useEffect(() => { |
|||
let routeTransitionTimer: any = null; |
|||
|
|||
const handleRouteChangeStart = (url: string) => { |
|||
clearTimeout(routeTransitionTimer); |
|||
routeTransitionTimer = setTimeout(() => { |
|||
if (currentRoute.current !== url) { |
|||
currentRoute.current = url; |
|||
setPendingRoute(url); |
|||
} |
|||
}, 100); |
|||
}; |
|||
const handleRouteChangeComplete = () => { |
|||
setPendingRoute(null); |
|||
clearTimeout(routeTransitionTimer); |
|||
}; |
|||
events.on('routeChangeStart', handleRouteChangeStart); |
|||
events.on('routeChangeComplete', handleRouteChangeComplete); |
|||
|
|||
return () => { |
|||
events.off('routeChangeStart', handleRouteChangeStart); |
|||
events.off('routeChangeComplete', handleRouteChangeComplete); |
|||
clearTimeout(routeTransitionTimer); |
|||
}; |
|||
}, []); |
|||
|
|||
return pendingRoute; |
|||
}; |
|||
|
|||
export default usePendingRoute; |
Loading…
Reference in new issue