Is there any solution to make localstorage setItem asynchronous way in javascript

Using an ionic application that checks auth-based tokens, storing the token in localstorage, it takes time to store between the transition to the next state - any solution for an asynchronous way to set a value in localstorage

window.localStorage.setItem('ChemistloggedInUser', JSON.stringify(data))
+4
source share
1 answer

localStorageis a synchronous API. You can delay the execution of a method setItemusing an object Promise, giving them asynchronous behavior:

const asyncLocalStorage = {
    setItem: function (key, value) {
        return Promise.resolve().then(function () {
            localStorage.setItem(key, value);
        });
    },
    getItem: function (key) {
        return Promise.resolve().then(function () {
            return localStorage.getItem(key);
        });
    }
};

// Demo
const data = Date.now() % 1000;
asyncLocalStorage.setItem('mykey', data).then(function () {
    return asyncLocalStorage.getItem('mykey');
}).then(function (value) {
    console.log('Value has been set to:', value);
});
console.log('waiting for value to become ' + data + 
            '. Current value: ', localStorage.getItem('mykey'));

See how it works on repl.it , as SO snippets do not allow use localStorage.

+6

Source: https://habr.com/ru/post/1672793/


All Articles