skip to Main Content

I’m trying to update an object property inside my localStorage but useStorage doesn’t update the object if it exists in the store.

in App.vue:

routeStore.query = {
  tab: 'products',
  subTab: 1,
  search: '',
  article: '',
}
console.log(routeStore.query)
console.log(localStorage.query)
useStorage('query', routeStore.query)
console.log(localStorage.query)

console:

Proxy(Object) {tab: 'products', subTab: 1, search: '', article: ''}
{"tab":"products","subTab":2,"search":"","article":""}
{"tab":"products","subTab":2,"search":"","article":""}

Desired outcome is for query.subTab to be 1. Am I doing it wrong?

2

Answers


  1. Ok, so by default useStorage doesn’t sync the default object with localStorage. See here https://vueuse.org/core/useStorage/#merge-defaults

    Try using mergeDefaults.

    routeStore.query = {
      tab: 'products',
      subTab: 1,
      search: '',
      article: '',
    }
    
    useStorage(
      'query',
      routeStore.query,
      localStorage,
      { mergeDefaults: true } // <--
    )
    
    Login or Signup to reply.
  2. You should use Merge Defaults option

    useStorage('query', routeStore.query,  localStorage, { mergeDefaults: true })
    

    Here is JSFiddle https://jsfiddle.net/12ctwmzg/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search