diff --git a/packages/app/src/hooks/useUrlQueryActiveKey.js b/packages/app/src/hooks/useUrlQueryActiveKey.js index 5098933c..a3c03aa1 100755 --- a/packages/app/src/hooks/useUrlQueryActiveKey.js +++ b/packages/app/src/hooks/useUrlQueryActiveKey.js @@ -1,27 +1,39 @@ import React from "react" -export default ({ - defaultKey = "0", - queryKey = "key", -}) => { - const [activeKey, setActiveKey] = React.useState(new URLSearchParams(window.location.search).get(queryKey) ?? defaultKey) +export default ({ defaultKey = "0", queryKey = "key" }) => { + const [activeKey, setActiveKey] = React.useState( + new URLSearchParams(window.location.search).get(queryKey) ?? defaultKey, + ) - const replaceQueryTypeToCurrentTab = (key) => { - if (!key) { - // delete query - return history.pushState(undefined, "", window.location.pathname) - } + const replaceQueryTypeToCurrentTab = (key) => { + if (!key) { + // delete query + return history.pushState(undefined, "", window.location.pathname) + } - return history.pushState(undefined, "", `?${queryKey}=${key}`) - } + return history.pushState(undefined, "", `?${queryKey}=${key}`) + } - const changeActiveKey = (key) => { - setActiveKey(key) - replaceQueryTypeToCurrentTab(key) - } + const changeActiveKey = (key) => { + setActiveKey(key) + replaceQueryTypeToCurrentTab(key) + } - return [ - activeKey, - changeActiveKey, - ] -} \ No newline at end of file + const onHistoryChange = () => { + const newActiveKey = new URLSearchParams(window.location.search).get( + queryKey, + ) + + setActiveKey(newActiveKey ?? defaultKey) + } + + React.useEffect(() => { + window.addEventListener("popstate", onHistoryChange) + + return () => { + window.removeEventListener("popstate", onHistoryChange) + } + }, []) + + return [activeKey, changeActiveKey] +}