Reactive Built-ins: `Date`, `URL`, and `URLSearchParams` in Svelte
Introduction to Reactive Built-ins
Using `SvelteDate` for Reactive Dates
SvelteDate is a reactive version of JavaScript’s built-in Date object. It allows you to work with dates in a way that automatically updates the UI whenever the date changes. Unlike regular Date objects, SvelteDate is mutable, meaning you can update its value directly without needing to reassign it.
Here’s an example of how to use SvelteDate to display the current time:
In this example, we create a SvelteDate instance called currentDate. The $effect rune sets up an interval that updates currentDate every second. Because SvelteDate is reactive, the UI automatically reflects the updated time without requiring additional logic. The cleanup function ensures the interval is cleared when the component is destroyed, preventing memory leaks.
When you run this code, you’ll see the current time displayed, updating every second.
Using `SvelteURL` and `URLSearchParams` for Reactive URLs
SvelteURL is a reactive version of JavaScript’s URL object. It allows you to work with URLs in a way that automatically updates the UI whenever the URL changes. Like SvelteDate, SvelteURL is mutable, so you can update its properties directly.
Here’s an example of how to use SvelteURL to manage and update query parameters:
In this example, we create a SvelteURL instance called url with an initial query string. The updateQueryParam function increments the value of the foo query parameter by 1. Because SvelteURL is reactive, the UI automatically updates to reflect the new URL whenever the query parameter changes.
When you run this code, you’ll see the current URL displayed, and clicking the button will increment the foo query parameter.
