Very lightweight way to get query params on your Alpine.js page. Good for storing data in the URL
import Spruce from '@ryangjchandler/spruce'
Spruce.store('settings', {})
export default Spruce
export var defaultSettings = {
someSetting: 'test'
}
// get settings
// ps. you might need something like this: https://stackoverflow.com/questions/14470516/javascript-running-code-once
var urlParams = new URLSearchParams(window.location.search)
let settingsFromURL = {}
Object.keys(defaultSettings).forEach((key, index) => {
if (urlParams.has(key)) {
var settingsParam: object | null = JSON.parse(urlParams.get(key))
if (settingsParam != null) {
Object.assign(settingsFromURL, { [key]: settingsParam })
}
} else {
Object.assign(settingsFromURL, { [key]: defaultSettings[key] })
}
})
Spruce.reset('settings', settingsFromURL)
// save settings
Object.keys(defaultSettings).forEach((key, index) => {
Spruce.watch(`settings.${key}`, (old, next) => {
setQueryStringParameter(key, encodeURIComponent(JSON.stringify(next)))
})
})
export const setQueryStringParameter = (name: string, value: string) => {
const params = new URLSearchParams(window.location.search)
params.set(name, value)
const url = decodeURIComponent(`${window.location.pathname}?${params}`)
window.history.replaceState({}, '', url)
return url
}