Consider a Vuex store using a plugin to save state to localStorage. What happens when the page reloads?
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ } }, plugins: [store => { store.subscribe((mutation, state) => { localStorage.setItem('count', state.count) }) }] })
Think about what the plugin does and what it does not do on page load.
The plugin saves the state to localStorage on mutation, but it does not restore the state when the store initializes. So on reload, the count resets to 0.
You want to initialize the Vuex store state with a saved count from localStorage or default to 0. Which option is correct?
Remember localStorage stores strings. You need a number for count.
parseInt converts the string to a number or returns NaN, which is falsy, so the || 0 fallback works correctly.
Given this Vuex plugin code, why does localStorage not update after calling a mutation?
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ } }, plugins: [store => { store.subscribe((mutation, state) => { localStorage.setItem('count', state.count) }) }] }) store.commit('increment') // localStorage.getItem('count') still returns '0'
Consider when the subscribe callback runs relative to mutation.
Vuex subscribe callbacks run after mutations, so the state.count should be updated. However, if the mutation is synchronous, localStorage should update. The issue is likely a misunderstanding: the code works as expected, so the problem is elsewhere.
Using this Vuex store with persisted state plugin, what is the value of state.count after a page reload?
const persistedState = store => { const saved = localStorage.getItem('count') if (saved) { store.replaceState({ count: Number(saved) }) } store.subscribe((mutation, state) => { localStorage.setItem('count', state.count) }) } const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ } }, plugins: [persistedState] }) store.commit('increment') // page reload happens here
Look at how replaceState uses the saved value on initialization.
The plugin reads the saved count from localStorage and replaces the store state with it on initialization. After committing increment once, count is 1 and saved. On reload, replaceState sets count to 1.
Why is store.replaceState() preferred over directly mutating store.state when restoring persisted state?
Think about Vuex reactivity and how state changes notify components.
replaceState replaces the entire state and triggers Vuex's reactivity system, ensuring components update. Directly mutating store.state bypasses Vuex's tracking and can cause inconsistent UI.