Created
February 1, 2024 13:23
-
-
Save raphaelameaume/44683ea40c2761c4d5e3506ce67980de to your computer and use it in GitHub Desktop.
Save/retrieve props with localStorage
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
function syncProps(props) { | |
return Object.keys(props).reduce((all, key) => { | |
const prop = { ...props[key] }; | |
const storageKey = `${key}`; | |
const { onChange = () => {} } = prop; | |
prop.onChange = (prop) => { | |
localStorage.setItem(storageKey, JSON.stringify(prop.value)); | |
onChange(prop); | |
}; | |
all[key] = prop; | |
if (localStorage.getItem(storageKey)) { | |
all[key].value = JSON.parse(localStorage.getItem(storageKey)); | |
} | |
return all; | |
}, {}); | |
} | |
export let props = syncProps({ | |
radius: { | |
value: 12, | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment