Bird
Raised Fist0
Vueframework~20 mins

Persisting store state in Vue - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Vuex Persistence Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does Vuex persist state with plugins?

Consider a Vuex store using a plugin to save state to localStorage. What happens when the page reloads?

Vue
const store = new Vuex.Store({
  state: { count: 0 },
  mutations: {
    increment(state) { state.count++ }
  },
  plugins: [store => {
    store.subscribe((mutation, state) => {
      localStorage.setItem('count', state.count)
    })
  }]
})
AThe count resets to 0 on reload because state is not restored automatically.
BThe count value doubles on each reload because the plugin runs twice.
CThe count value is saved but causes an error on reload due to missing initialization.
DThe count value is restored from localStorage automatically on reload.
Attempts:
2 left
💡 Hint

Think about what the plugin does and what it does not do on page load.

📝 Syntax
intermediate
2:00remaining
Which code correctly initializes Vuex state from localStorage?

You want to initialize the Vuex store state with a saved count from localStorage or default to 0. Which option is correct?

Astate: { count: parseInt(localStorage.getItem('count')) || 0 }
Bstate: { count: Number(localStorage.getItem('count')) || 0 }
Cstate: { count: localStorage.getItem('count') || 0 }
Dstate: { count: JSON.parse(localStorage.getItem('count')) || 0 }
Attempts:
2 left
💡 Hint

Remember localStorage stores strings. You need a number for count.

🔧 Debug
advanced
2:00remaining
Why does the persisted state not update after mutation?

Given this Vuex plugin code, why does localStorage not update after calling a mutation?

Vue
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'
AThe plugin subscribes after the mutation, so it misses the update.
BThe mutation updates state.count, but localStorage stores the old value because subscribe callback runs before mutation.
CThe mutation changes state.count but localStorage.setItem is not called due to a typo.
DThe mutation is asynchronous, so localStorage updates before state changes.
Attempts:
2 left
💡 Hint

Consider when the subscribe callback runs relative to mutation.

❓ state_output
advanced
2:00remaining
What is the value of state after reload with persisted state plugin?

Using this Vuex store with persisted state plugin, what is the value of state.count after a page reload?

Vue
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
ANaN
B0
Cundefined
D1
Attempts:
2 left
💡 Hint

Look at how replaceState uses the saved value on initialization.

🧠 Conceptual
expert
2:00remaining
Why use Vuex replaceState for persisting state?

Why is store.replaceState() preferred over directly mutating store.state when restoring persisted state?

AreplaceState automatically saves the state to localStorage, direct mutation does not.
BDirect mutation of store.state is forbidden and causes runtime errors, replaceState avoids errors.
CreplaceState triggers Vuex reactivity and updates all subscribers properly, while direct mutation does not.
DreplaceState is faster because it skips Vuex mutation handlers, while direct mutation is slow.
Attempts:
2 left
💡 Hint

Think about Vuex reactivity and how state changes notify components.

Practice

(1/5)
1. What is the main purpose of persisting store state in a Vue application?
easy
A. To speed up the app by caching components
B. To keep the app data saved even after refreshing or closing the browser
C. To automatically update the UI without user input
D. To prevent users from logging out

Solution

  1. Step 1: Understand what persisting store state means

    Persisting store state means saving the app's data so it does not disappear when the page reloads or the browser closes.
  2. Step 2: Identify the main benefit

    This helps keep user data or app settings intact, improving user experience.
  3. Final Answer:

    To keep the app data saved even after refreshing or closing the browser -> Option B
  4. Quick Check:

    Persisting state = saving data after refresh [OK]
Hint: Persisting means saving data beyond page reloads [OK]
Common Mistakes:
  • Confusing persisting with caching UI components
  • Thinking it automatically updates UI without user action
  • Believing it prevents user logout directly
2. Which of the following is the correct way to add the vuex-persistedstate plugin to a Vuex store?
easy
A. import createPersistedState from 'vuex-persistedstate'; const store = createStore({ plugins: createPersistedState });
B. import createPersistedState from 'vuex-persistedstate'; const store = createStore({ persist: createPersistedState() });
C. import createPersistedState from 'vuex-persistedstate'; const store = createStore({ plugins: [createPersistedState()] });
D. import createPersistedState from 'vuex-persistedstate'; const store = createStore({ plugins: [createPersistedState] });

Solution

  1. Step 1: Recall the plugin usage syntax

    The vuex-persistedstate plugin is imported as a function and added inside the plugins array when creating the store.
  2. Step 2: Check the correct syntax

    import createPersistedState from 'vuex-persistedstate'; const store = createStore({ plugins: [createPersistedState()] }); correctly imports and calls createPersistedState() inside the plugins array.
  3. Final Answer:

    import createPersistedState from 'vuex-persistedstate'; const store = createStore({ plugins: [createPersistedState()] }); -> Option C
  4. Quick Check:

    Plugin added as function in plugins array [OK]
Hint: Plugins go inside plugins array, called as functions [OK]
Common Mistakes:
  • Putting plugin directly as object property instead of in plugins array
  • Not calling the plugin function with ()
  • Passing plugin without wrapping in array
3. Given this Vuex store setup with vuex-persistedstate:
import { createStore } from 'vuex';
import createPersistedState from 'vuex-persistedstate';

const store = createStore({
  state() {
    return { count: 0 };
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  },
  plugins: [createPersistedState()]
});

store.commit('increment');

// After page reload, what is the value of store.state.count?
medium
A. 1
B. Error
C. undefined
D. 0

Solution

  1. Step 1: Understand what happens on commit

    The mutation increment increases count from 0 to 1.
  2. Step 2: Effect of vuex-persistedstate plugin

    This plugin saves the state to localStorage, so after page reload, the state is restored with count still 1.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    Persisted state restores count = 1 after reload [OK]
Hint: Persisted state keeps mutations after reload [OK]
Common Mistakes:
  • Assuming state resets to initial value after reload
  • Thinking plugin does not save mutations
  • Confusing undefined or error with normal behavior
4. You added vuex-persistedstate to your Vuex store but the state is not saved after refresh. Which of these is the most likely cause?
medium
A. You forgot to call the plugin function inside the plugins array
B. You did not import Vuex correctly
C. You used mutations instead of actions
D. You did not define the initial state

Solution

  1. Step 1: Check plugin usage

    If the plugin is added without calling it as a function (missing parentheses), it won't activate and save state.
  2. Step 2: Verify other options

    Importing Vuex correctly, using mutations, and defining initial state are unrelated to plugin activation.
  3. Final Answer:

    You forgot to call the plugin function inside the plugins array -> Option A
  4. Quick Check:

    Plugin must be called as function to work [OK]
Hint: Always call plugin with () inside plugins array [OK]
Common Mistakes:
  • Adding plugin without parentheses
  • Blaming mutations or initial state for persistence issues
  • Ignoring plugin import errors
5. You want to persist only the user part of your Vuex state and store it in sessionStorage instead of localStorage. Which is the correct way to configure vuex-persistedstate?
hard
A. plugins: [createPersistedState({ only: ['user'], storage: window.sessionStorage })]
B. plugins: [createPersistedState({ paths: ['user'], storage: 'sessionStorage' })]
C. plugins: [createPersistedState({ keys: ['user'], storage: sessionStorage })]
D. plugins: [createPersistedState({ paths: ['user'], storage: window.sessionStorage })]

Solution

  1. Step 1: Use the correct option to select parts of state

    The paths option specifies which parts of the state to save, so paths: ['user'] is correct.
  2. Step 2: Set storage to sessionStorage correctly

    The storage option expects the storage object, so window.sessionStorage is correct.
  3. Final Answer:

    plugins: [createPersistedState({ paths: ['user'], storage: window.sessionStorage })] -> Option D
  4. Quick Check:

    Use paths and window.sessionStorage for selective session storage [OK]
Hint: Use paths array and window.sessionStorage for selective session saving [OK]
Common Mistakes:
  • Using string 'sessionStorage' instead of window.sessionStorage object
  • Using wrong option names like only or keys
  • Not specifying paths to limit saved state
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard