0

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?

Tolbxela
  • 4,767
  • 3
  • 21
  • 42
Artur Müller Romanov
  • 4,417
  • 10
  • 73
  • 132
  • Console is unnecessary contains up-to-date info. Don't use it to debug objects. It's unknown if it's incorrect observation that's the problem here, or something else. See https://stackoverflow.com/questions/17546953/cant-access-object-property-even-though-it-shows-up-in-a-console-log – Estus Flask May 16 '23 at 10:04

2 Answers2

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 } // <--
)
Tuan Pham
  • 1,171
  • 2
  • 15
  • 27
  • This works but strangely it does so only once. When I want to change the `subTab` propery consecutively, it just stays at the value of the initial change. Any idea what could be causing this? – Artur Müller Romanov May 16 '23 at 08:33
  • @ArturMüllerRomanov useStorage isn't a glorified localStorage.setItem You don't sync routeStore and a store that useStorage returns, you actually ignore the latter. There should be a single source of truth, and it has to be be a store that useStorage returns, there may be no need for routeStore depending on your case – Estus Flask May 16 '23 at 10:35
  • This part about sync is misleading because default object isn't synced at all. It's copied. – Estus Flask May 16 '23 at 10:39
0

You should use Merge Defaults option

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

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

Tolbxela
  • 4,767
  • 3
  • 21
  • 42