L
L
lacront2018-09-25 10:33:33
Vue.js
lacront, 2018-09-25 10:33:33

Using async/await with localStorage?

Can you please tell me if it makes sense to use async / await when receiving data from localStorage and saving it?
Did something like this:

let apiLocalStorage = {
  initialState: async function(){
    return await JSON.parse(localStorage.tasks || '[]');
  },
  saveState: async function(tasks){
    localStorage.tasks = JSON.stringify(tasks)
  },
};

apiLocalStorage.initialState().then((tasks) => {
  state.todos = tasks;
});

One of the mutations
const state = {
  todos: [],
};

const mutations = {
  addNew(state, payload) {
    state.todos = [...state.todos, payload];
    apiLocalStorage.saveState(state.todos)
  },
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
r37r0m0d3l, 2020-10-30
@r37r0m0d3l

localStorage is synchronous and will block JavaScript execution
Options:
1). We block the entire page with a spinner that runs on CSS animations and does not call JavaScript. perform operations on localStorage.
2). Rejection of localStorage in favor of Web Storage.
3). Passing data through an iframe of the same domain. Example: https://stackoverflow.com/questions/37917483/get-l... . Most likely it will be blocked by browser plugins or stop working due to new Content Security Policies.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question