47ng / nuqs

Type-safe search params state manager for React frameworks - Like useState, but stored in the URL query string.
https://nuqs.47ng.com
MIT License
5k stars 109 forks source link

Keys with special characters are not encoded, reading encoded keys result in incorrect state after sync operation #599

Closed lecbyjak closed 3 months ago

lecbyjak commented 3 months ago

Context

What's your version of nuqs?

    "next-usequerystate": "^1.17.4",

Next.js information (obtained by running next info):

    Operating System:
      Platform: darwin
      Arch: arm64
      Version: Darwin Kernel Version 23.5.0: Wed May  1 20:16:51 PDT 2024; root:xnu-10063.121.3~5/RELEASE_ARM64_T8103
    Binaries:
      Node: 18.19.1
      npm: 10.2.4
      Yarn: N/A
      pnpm: 8.15.9
    Relevant packages:
      next: 13.4.1
      eslint-config-next: 13.4.1
      react: 18.2.0
      react-dom: 18.2.0

Are you using:

Description

Having a special character (&) in key, causes url read issues.

Reproduction

When using following keyMap the keys in the URL are not encoded resulting in incorrect read/sync

const [traits, setTraits] = useQueryStates({
// this object is dynamic based on API response, but for testing purpose we use hardcoded value
['Duration & Location']: parseAsString
});

When using following keyMap with encoded keys, the URL is correctly encoded, but after sync operation 'useQueryStates' returns traits as { 'Duration%20%26%20Location': null }. Using a debugger I saw that the query state object was { 'Duration+%26+Location': null }

const [traits, setTraits] = useQueryStates({
[encodeURIComponent('Duration & Location')]: parseAsString
});

I have also tried to use following keyMap but with the same result

const [traits, setTraits] = useQueryStates({
['Duration & Location'.replace(/&/g, '%26')]: parseAsString
});
franky47 commented 3 months ago

Thanks for the report. It looks like the key should be encoded in the same way as the value here: https://github.com/47ng/nuqs/blob/next/packages%2Fnuqs%2Fsrc%2Furl-encoding.ts#L7

I'll run some tests and come back to you.

franky47 commented 3 months ago

I have published a fix in #600 via a snapshot release, could you give it a try and let me know if it solves your problem?

npm install nuqs@1.17.8-snapshot.2024-08-07.fb4c41b3
lecbyjak commented 3 months ago

Awsome. Works!

Thanks for super quick response 💚

github-actions[bot] commented 3 months ago

:tada: This issue has been resolved in version 1.17.8 :tada:

The release is available on:

Your semantic-release bot :package::rocket: