📖 Scenario: You are building a simple Vue 3 app that keeps track of a user's favorite color. You want the app to remember the favorite color even if the user refreshes the page or closes and reopens the browser.
🎯 Goal: Create a Vue 3 store using the Composition API that saves the favorite color in localStorage and loads it when the app starts.
📋 What You'll Learn
Create a reactive store object with a favoriteColor property
Add a function to update favoriteColor
Save favoriteColor to localStorage whenever it changes
Load favoriteColor from localStorage when the store initializes
💡 Why This Matters
🌍 Real World
Many web apps need to remember user settings like themes, language, or preferences. Persisting store state with localStorage is a simple way to keep data across sessions.
💼 Career
Understanding how to persist state in frontend frameworks like Vue is essential for building user-friendly, real-world applications that feel seamless and personalized.
Progress0 / 4 steps
1
Create the initial store state
Create a Vue 3 store file named useColorStore.js. Inside it, import ref from vue and create a reactive variable called favoriteColor initialized to the string "blue".
Vue
Hint
Use ref('blue') to create a reactive string variable.
2
Add a function to update the favorite color
Below the favoriteColor variable, add a function called setFavoriteColor that takes a parameter color and sets favoriteColor.value to color.
Vue
Hint
Define a function that changes the reactive variable's value.
3
Save favoriteColor to localStorage when it changes
Import watch from vue. Use watch to observe favoriteColor. Inside the watcher callback, save favoriteColor.value to localStorage with the key "favoriteColor".
Vue
Hint
Use watch to react to changes and save the new value.
4
Load favoriteColor from localStorage on initialization
Before exporting, check if localStorage has a value for the key "favoriteColor". If it exists, set favoriteColor.value to that stored value. Then export favoriteColor and setFavoriteColor from the module.
Vue
Hint
Use localStorage.getItem to load saved data and export the store variables.
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
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.
Step 2: Identify the main benefit
This helps keep user data or app settings intact, improving user experience.
Final Answer:
To keep the app data saved even after refreshing or closing the browser -> Option B
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
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.
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.
Final Answer:
import createPersistedState from 'vuex-persistedstate';
const store = createStore({
plugins: [createPersistedState()]
}); -> Option C
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
Step 1: Understand what happens on commit
The mutation increment increases count from 0 to 1.
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.
Final Answer:
1 -> Option A
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
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.
Step 2: Verify other options
Importing Vuex correctly, using mutations, and defining initial state are unrelated to plugin activation.
Final Answer:
You forgot to call the plugin function inside the plugins array -> Option A
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
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.
Step 2: Set storage to sessionStorage correctly
The storage option expects the storage object, so window.sessionStorage is correct.
Final Answer:
plugins: [createPersistedState({ paths: ['user'], storage: window.sessionStorage })] -> Option D
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 unknownstrongwhile earning +1 Grip toward your certificate.