@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
57 lines (56 loc) • 1.83 kB
JavaScript
"use client";
import _URL from "core-js-pure/stable/url/index.js";
import _URLSearchParams from "core-js-pure/stable/url-search-params/index.js";
import { useCallback } from 'react';
import useStep from "./useStep.js";
import { useIsomorphicLayoutEffect as useLayoutEffect } from "../../../../shared/helpers/useIsomorphicLayoutEffect.js";
export default function useQueryLocator(id = undefined) {
const {
setFormError
} = useStep(id);
const name = id ? `${id}-step` : 'step';
const onStepChange = useCallback(index => {
try {
const url = new _URL(window.location.href);
url.searchParams.set(name, String(index));
window.history.pushState({}, '', url.toString());
} catch (error) {
setFormError(error);
}
}, [name, setFormError]);
const {
setActiveIndex
} = useStep(id, {
onStepChange
});
const getIndex = useCallback(() => {
try {
const searchParams = new _URLSearchParams(window.location.search);
return parseFloat(searchParams.get(name));
} catch (error) {
setFormError(error);
}
}, [name, setFormError]);
useLayoutEffect(() => {
try {
const popstateListener = () => {
const routerIndex = getIndex();
if (!isNaN(routerIndex)) {
setActiveIndex === null || setActiveIndex === void 0 || setActiveIndex(routerIndex, {
skipStepChangeCallFromHook: true,
skipStepChangeCallBeforeMounted: true
});
}
};
popstateListener();
window.addEventListener('popstate', popstateListener);
return () => window.removeEventListener('popstate', popstateListener);
} catch (error) {
setFormError(error);
}
}, [getIndex, id, setActiveIndex, setFormError]);
return {
getIndex
};
}
//# sourceMappingURL=useQueryLocator.js.map