Last active
October 26, 2023 15:31
-
-
Save moimikey/07501755bcba3aa409b0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Michael Scott Hertzberg <[email protected]> (http://hertzber.gs) | |
* | |
* recursively check for set localStorage value every 100ms. | |
* this will also safely clear the timeout once found. | |
* can be used callback style or directly. | |
* functionally pure. | |
*/ | |
function waitForLocalStorage(key, cb, timer) { | |
if (!localStorage.getItem(key)) return (timer = setTimeout(waitForLocalStorage.bind(null, key, cb), 100)) | |
clearTimeout(timer) | |
if (typeof cb !== 'function') return localStorage.getItem(key) | |
return cb(localStorage.getItem(key)) | |
} |
usage:
waitForLocalStorage('coolProperty', function (value) {
console.log('coolProperty', value);
});
the 3rd argument isn't necessary.
Actually you can use something like this.
https://stackoverflow.com/a/42922083
not working
The issue with the original gist is the following:
if (!localStorage.getItem(key)) return (timer = setTimeout(waitForLocalStorage.bind(null, key), 100))
Fix:
waitForLocalStorage.bind(null, key, cb )
The callback is undefined after the recursion if we don't pass it over
Thanks @moimikey for the useful snippet - sometimes we "don't know" when a local storage item becomes available, it could be set by a separate component async for example
correct gist following @dragGH102 's fix:
function waitForLocalStorage(key, cb, timer) {
if ( ! localStorage.getItem( key ) ) {
return timer = setTimeout(
waitForLocalStorage.bind( null, key, cb ),
100
)
}
clearTimeout( timer )
if ( typeof cb !== 'function' ) {
return localStorage.getItem( key )
}
return cb( localStorage.getItem( key ) )
}
@dragGH102 thanks! good catch! gist has been updated.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
can you provide an example how to use it?