The searchParams
variable is an instance of the SearchParamsManager
class. It allows seamless manipulation of search query strings, mimicking the behavior of frameworks like Next.js, including dynamic updates, replacement, and change listeners—all without reloading the page.
Methods
get(key)
Retrieves the value of a specific search parameter from the current URL.
- Parameters:
key
- The name of the search parameter. - Returns: The parameter value or
null
if not found.
set(key, value)
Updates or adds a search parameter to the URL. This method uses history.pushState
to avoid page reloads.
- Parameters:
key
- The name of the parameter.value
- The new value to assign.
delete(key)
Removes a specific search parameter from the URL.
- Parameters:
key
- The parameter to remove.
replace(params)
Replaces all current search parameters with the given object. Useful for bulk updates or resetting.
- Parameters:
params
- An object where keys are parameter names and values are their replacements. If a value isnull
, that key will be skipped.
listen(callback)
Subscribes to search parameter changes and invokes the provided callback with the latest URLSearchParams
instance.
- Parameters:
callback
- Function to execute when search parameters change.
enablePopStateListener()
Enables listening for browser navigation events (back/forward buttons) to keep the UI in sync with the URL.
Usage
<script>
// Read parameter
console.log(searchParams.get('page'));
// Set parameter
searchParams.set('page', '2');
// Replace all parameters
searchParams.replace({ page: '1', sort: 'asc' });
// Listen for changes
searchParams.listen((params) => {
console.log('Search updated:', params.toString());
});
// Enable back/forward sync
searchParams.enablePopStateListener();
</script>
Conclusion
The SearchParamsManager
class simplifies working with query strings in Prisma PHP. It provides a declarative, stateful, and reusable approach to managing URL search parameters, enhancing user experience and deep-linking capabilities without relying on a full framework.