47ng / nuqs

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

Reset to Default State #680

Open anaclumos opened 3 days ago

anaclumos commented 3 days 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 3 days 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