47ng / 47ng/nuqs

[bug] dynamic default values do not properly update

未關閉
#1,193 2 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視
bug
主要語言
TypeScript
星號
10.8k
分支
294
平均合併
1 天 16 小時
30 天內合併 PR
21

描述

## Context

What's your version of `nuqs`?

```
2.7.2
```

What framework are you using?

- ✅ Next.js (app router)

Which version of your framework are you using?

next 14.2.33

## Description

There are 2 issues related to dynamic default values (changing the value passed to `withDefault` at runtime). From some trial and error, it looks like these both worked in nuqs 2.3.0 and are broken in 2.3.1.

1. If the defaultValue changes at runtime, it partially updates but is out of sync. The new default value will clear the query param, but will set the value to the old default value.

It looks like this is fixed by adding `defaultValues` to the dependency array [here](https://github.com/47ng/nuqs/blob/026eaa475b7a1ed8820cb21432d1c69ae2ab5223/packages/nuqs/src/useQueryStates.ts#L268)

2. If the default value (and by extension, the value) is an object, the default value never updates. This appears to be because the dependency array tries to check it as a string value, meaning no matter what, it sees an unchanging `[object Object]`

Changing [this line](https://github.com/47ng/nuqs/blob/026eaa475b7a1ed8820cb21432d1c69ae2ab5223/packages/nuqs/src/useQueryStates.ts#L110) to `.map(({ defaultValue }) => JSON.stringify(defaultValue))` seems to fix that

## Reproduction

Example: Steps to reproduce the behavior:

1. Go to https://codesandbox.io/p/devbox/g8gmlp
2. Change the first input to "def"
3. Type "def" into the second input
4. The query param is cleared, but the input changes to "abc" (the default value in the code)

貢獻指南

開啟貢獻指南

研究方向

此 issue 指向 packages/nuqs/src/useQueryStates.ts 中的特定行(第 268 行和第 110 行)。首先檢查 defaultValues 的依賴陣列邏輯,以及物件預設值的序列化。提供的 CodeSandbox 連結中的重現展示了此 bug。若要驗證修正,請執行 useQueryStates 的現有測試,並為使用物件的動態預設值建立一個新的測試案例。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
next.js
領域
frontend
Issue 類型
缺陷
難度
3/5
預估耗時
1-2 天
活躍度
停滯
描述清晰度
描述清楚
新手友好度
55/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。