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
4.91k stars 105 forks source link

Reset to Default State #680

Closed anaclumos closed 1 month ago

anaclumos commented 1 month ago

How can I reset to the default state?

// My default values are stored here:

import {
  parseAsFloat,
  createSearchParamsCache
} from 'nuqs/server'

export const coordinatesParsers = {
  lat: parseAsFloat.withDefault(45.18) // here
  lng: parseAsFloat.withDefault(5.72) // here
}

export const coordinatesCache = createSearchParamsCache(coordinatesParsers)
franky47 commented 1 month ago

Use null in the state updater function: it will remove the key from the URL and return the default value.

https://nuqs.47ng.com/docs/basic-usage#default-values

For useQueryStates, you can do it per key or for all the ones managed by the hook at once:

const [coordinates, setCoordinates] = useQueryStates(coordinatesParsers)

setCoordinates({ lat: null }) // only reset lat
setCoordinates(null) // reset both lat & lng, leave other search params as-is