From 98fa3eb2146445890b42ada58f3bf47276bbb8f9 Mon Sep 17 00:00:00 2001 From: Artur Drobinskiy Date: Wed, 24 Aug 2022 15:20:39 +0700 Subject: [PATCH] fix changing parameter to an empty array (should clear the parameter) --- example/ArrayParamPage.tsx | 7 +++++++ src/useQueryParams.ts | 12 ++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/example/ArrayParamPage.tsx b/example/ArrayParamPage.tsx index 1ff1e77..f38c498 100644 --- a/example/ArrayParamPage.tsx +++ b/example/ArrayParamPage.tsx @@ -31,6 +31,13 @@ export const ArrayParamPage = () => { > Change ids to 3,4 +
Id: {queryParams.id} diff --git a/src/useQueryParams.ts b/src/useQueryParams.ts index 91ca3d2..46f408b 100644 --- a/src/useQueryParams.ts +++ b/src/useQueryParams.ts @@ -70,10 +70,14 @@ export const useQueryParams = ( Object.keys(values).forEach((key) => { const keyValue = (encoded as any)[key]; if (Array.isArray(keyValue)) { - keyValue.forEach((v, index) => { - if (index === 0) searchParamsRef.current.set(key, v); - else searchParamsRef.current.append(key, v); - }); + if (keyValue.length > 0) { + keyValue.forEach((v, index) => { + if (index === 0) searchParamsRef.current.set(key, v); + else searchParamsRef.current.append(key, v); + }); + } else { + searchParamsRef.current.delete(key); + } } else { if (keyValue === undefined || keyValue === null) { searchParamsRef.current.delete(key);