diff --git a/lib/setSearchParams.ts b/lib/setSearchParams.ts index 0d69d7116..6f1fa0631 100644 --- a/lib/setSearchParams.ts +++ b/lib/setSearchParams.ts @@ -24,3 +24,31 @@ export const setSearchParams = ( }${params.toString()}` ); }; + +export const setManySearchParams = ( + newParams: { key: string; value: string | string[] | undefined }[] +) => { + const url = new URL(window.location.href); + const params = new URLSearchParams(url.search); + + newParams.forEach(({ key, value }) => { + if (!value) { + params.delete(key); + } else if (Array.isArray(value)) { + params.delete(key); + value.forEach((element) => { + params.append(key, element); + }); + } else { + params.set(key, value); + } + }); + + history.replaceState( + {}, + "", + `${window.location.pathname}${ + Array.from(params.entries()).length ? "?" : "" + }${params.toString()}` + ); +}; diff --git a/pages/maps.tsx b/pages/maps.tsx index a43842d68..8abb6e1c0 100644 --- a/pages/maps.tsx +++ b/pages/maps.tsx @@ -27,6 +27,7 @@ import ModeImage from "components/common/ModeImage"; import MyContainer from "components/common/MyContainer"; import SubText from "components/common/SubText"; import { stages } from "lib/lists/stages"; +import { setManySearchParams } from "lib/setSearchParams"; import { useRouter } from "next/router"; import { ChangeEvent, Fragment, useEffect, useState } from "react"; import { FiCheck, FiFilter, FiRotateCw } from "react-icons/fi"; @@ -69,14 +70,10 @@ const MapsGeneratorPage = () => { } const poolForUrl = (stagesSelectedForUrl: Record) => { - return Object.entries(stagesSelectedForUrl).reduce( - (acc: Record, cur) => { - if (cur[1].length) acc[cur[0]] = cur[1].join(","); - - return acc; - }, - {} - ); + return Object.entries(stagesSelectedForUrl).map(([key, stages]) => ({ + key, + value: stages.join(","), + })); }; useEffect(() => { @@ -108,10 +105,7 @@ const MapsGeneratorPage = () => { const newStagesSelected = { ...stagesSelected, [stage]: newArray }; setStagesSelected(newStagesSelected); - router.replace({ - pathname: "/maps", - query: poolForUrl(newStagesSelected), - }); + setManySearchParams(poolForUrl(newStagesSelected)); }; const shuffled = (array: string[]) => { @@ -228,11 +222,7 @@ const MapsGeneratorPage = () => { if (!buttonIsAdd) delete newStagesSelected[stage]; setStagesSelected(newStagesSelected); - - router.replace({ - pathname: "/maps", - query: poolForUrl(newStagesSelected), - }); + setManySearchParams(poolForUrl(newStagesSelected)); }} > {buttonIsAdd ? All : Clear}