nextjs13-router-events
Version:
Provides NextJS 13 router events compatible with the App Router
31 lines (30 loc) • 1.42 kB
JavaScript
import { useEffect } from 'react';
import { useRouteChangeContext } from '../context/RouteChangeProvider';
var useRouteChange = function (options) {
var _a = useRouteChangeContext(), routeChangeStartCallbacks = _a.routeChangeStartCallbacks, routeChangeCompleteCallbacks = _a.routeChangeCompleteCallbacks;
useEffect(function () {
// add callback to the list of callbacks and persist it
if (options.onRouteChangeStart) {
routeChangeStartCallbacks.push(options.onRouteChangeStart);
}
if (options.onRouteChangeComplete) {
routeChangeCompleteCallbacks.push(options.onRouteChangeComplete);
}
return function () {
// Find the callback in the array and remove it.
if (options.onRouteChangeStart) {
var index = routeChangeStartCallbacks.indexOf(options.onRouteChangeStart);
if (index > -1) {
routeChangeStartCallbacks.splice(index, 1);
}
}
if (options.onRouteChangeComplete) {
var index = routeChangeCompleteCallbacks.indexOf(options.onRouteChangeComplete);
if (index > -1) {
routeChangeCompleteCallbacks.splice(index, 1);
}
}
};
}, [options, routeChangeStartCallbacks, routeChangeCompleteCallbacks]);
};
export default useRouteChange;