Code (I don't want to write such an annoying code any more.)
二度と書きたくないひどいコード
51 |
52 | ```ts
53 | // before
54 | const removeQuery = (
55 | query: ParsedUrlQuery,
56 | key: string,
57 | pred: string,
58 | ) => {
59 | const value = query[key];
60 |
61 | // if empty, leave query as it is.
62 | if (!value) return query;
63 | if (Array.isArray(value)) {
64 | if (value.length === 0) return query;
65 |
66 | // if non-empty array of string
67 | return { ...acc, [key]: value.filter((s) => s !== pred) };
68 | }
69 |
70 | // if single string (not empty)
71 | return { ...acc, [key]: (s !== value) ? value : [] };
72 | };
73 | ```
74 |
75 |
76 |
77 |
78 | ### After
79 |
80 | ```ts
81 | // after
82 | router.push(
83 | removeQueryParam({
84 | item_type: "book",
85 | })(router.query),
86 | );
87 | ```
88 |
89 | ## Keeping some params (or Next.js's dynamic routes) from being reset