Repository navigation
Expand file tree
/
Copy pathusePendingRoute.ts
More file actions
51 lines (44 loc) · 1.51 KB
/
Copy pathusePendingRoute.ts
File metadata and controls
51 lines (44 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*/
import {useRouter} from 'next/router';
import {useState, useRef, useEffect} from 'react';
const usePendingRoute = () => {
const {events} = useRouter();
const [pendingRoute, setPendingRoute] = useState<string | null>(null);
const currentRoute = useRef<string | null>(null);
useEffect(() => {
let routeTransitionTimer: any = null;
const handleRouteChangeStart = (url: string) => {
clearTimeout(routeTransitionTimer);
routeTransitionTimer = setTimeout(() => {
if (currentRoute.current !== url) {
currentRoute.current = url;
setPendingRoute(url);
}
}, 100);
};
const handleRouteChangeEnd = () => {
currentRoute.current = null;
setPendingRoute(null);
clearTimeout(routeTransitionTimer);
};
events.on('routeChangeStart', handleRouteChangeStart);
events.on('routeChangeComplete', handleRouteChangeEnd);
events.on('routeChangeError', handleRouteChangeEnd);
return () => {
events.off('routeChangeStart', handleRouteChangeStart);
events.off('routeChangeComplete', handleRouteChangeEnd);
events.off('routeChangeError', handleRouteChangeEnd);
clearTimeout(routeTransitionTimer);
};
}, [events]);
return pendingRoute;
};
export default usePendingRoute;