Skip to content

Instantly share code, notes, and snippets.

@chapmanjacobd
Last active June 16, 2020 05:58
Show Gist options
  • Save chapmanjacobd/a1b62c6a0892bca02e8e301c52812517 to your computer and use it in GitHub Desktop.
Save chapmanjacobd/a1b62c6a0892bca02e8e301c52812517 to your computer and use it in GitHub Desktop.
Alpine.js + Spruce URL Query Params

Very lightweight way to get query params on your Alpine.js page. Good for storing data in the URL

store.ts

import Spruce from '@ryangjchandler/spruce'

Spruce.store('settings', {})

export default Spruce

load-from-URL.ts

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)))
    })
})

fn.ts

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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment