Last active
October 7, 2024 16:53
-
-
Save trevorhreed/73eccb27f61f344970d04a9d0151501e to your computer and use it in GitHub Desktop.
A little state manager that does not scale. Uses localStorage and proxies.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const encode = value => btoa(JSON.stringify(value)) | |
export const decode = value => JSON.parse(atob(value)) | |
export const save = (key, value) => localStorage.setItem(key, encode(value)) | |
export const load = key => decode(localStorage.getItem(key) ?? btoa('{}')) | |
export const estate = (state = {}, { | |
localStorageKey = 'state', | |
} = {}) => { | |
const isProxy = Symbol('isProxy') | |
const handler = { | |
get(target, prop, receiver) { | |
if (key === isProxy) return true | |
const value = target[prop] | |
if (value instanceof Function) { | |
return function (...args) { | |
return value.apply(this === receiver ? target : this, args) | |
} | |
} | |
return value instanceof Object && !value[isProxy] | |
? new Proxy(value, handler) | |
: value | |
}, | |
set(target, prop, value, receiver) { | |
target[prop] = value | |
save(localStorageKey, state) | |
return true | |
} | |
} | |
const value = new Proxy({ ...load(localStorageKey), ...state }, handler) | |
save(localStorageKey, value) | |
return value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment