Bird
Raised Fist0
Vueframework~20 mins

Actions for modifying state in Vue - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Vue State Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when this Vue action is dispatched?

Consider a Vue 3 store with this action to increment a counter asynchronously. What will be the value of state.count after dispatching incrementAsync once?

Vue
import { reactive } from 'vue'

const state = reactive({ count: 0 })

const actions = {
  incrementAsync() {
    setTimeout(() => {
      state.count++
    }, 1000)
  }
}

actions.incrementAsync()

// After 1 second, what is state.count?
A0 immediately, then 1 after 1 second
B1 immediately
C0 forever, no change
DThrows an error because state is reactive
Attempts:
2 left
💡 Hint

Think about when setTimeout runs and when the state changes.

📝 Syntax
intermediate
2:00remaining
Which option correctly defines a Vue action that commits a mutation?

In Vue 3 with Composition API, which code snippet correctly defines an action that commits a mutation to update state?

Aconst actions = { updateName(name) { commit('setName', name) } }
Bconst actions = { updateName(context, name) { context.commit('setName', name) } }
Cconst actions = { updateName(context, name) { context.dispatch('setName', name) } }
Dconst actions = { updateName(state, name) { state.name = name } }
Attempts:
2 left
💡 Hint

Remember that actions receive a context object to commit mutations.

🔧 Debug
advanced
2:00remaining
Why does this Vue action not cause a UI update?

Given this Vue 3 store code, why does calling actions.increment() not cause a UI update for state.count?

Vue
import { reactive } from 'vue'

const state = reactive({ count: 0 })

const actions = {
  increment() {
    state.count += 1
  }
}

// Called somewhere: actions.increment()
ABecause the state object is not exported or used in a component
BBecause actions must use a commit function to change state
CBecause state is reactive, direct mutation inside actions is ignored
DBecause the increment function is not bound to the store context
Attempts:
2 left
💡 Hint

Think about how Vue reactivity works and what triggers UI updates.

❓ state_output
advanced
2:00remaining
What is the final state after dispatching these Vue actions?

Given this Vue 3 store code, what is the value of state.items after calling actions.addItem('apple') then actions.removeItem('apple')?

Vue
import { reactive } from 'vue'

const state = reactive({ items: [] })

const actions = {
  addItem(item) {
    state.items.push(item)
  },
  removeItem(item) {
    const index = state.items.indexOf(item)
    if (index !== -1) {
      state.items.splice(index, 1)
    }
  }
}

actions.addItem('apple')
actions.removeItem('apple')
A['apple', 'apple']
B['apple']
Cundefined
D[] (empty array)
Attempts:
2 left
💡 Hint

Think about how push and splice affect the array.

🧠 Conceptual
expert
2:00remaining
Why use actions instead of directly mutating state in Vue 3?

In Vue 3, why is it recommended to use actions to modify state instead of changing state directly in components?

ADirect mutation breaks Vue reactivity and stops UI updates
BDirect state mutation is forbidden and causes runtime errors
CActions centralize state changes, making them easier to track and debug
DActions automatically optimize performance by batching updates
Attempts:
2 left
💡 Hint

Think about maintainability and debugging in larger apps.

Practice

(1/5)
1. In Vue, what is the main purpose of an action in state management?
easy
A. To define computed properties for reactive data
B. To perform asynchronous operations and then commit mutations to change state
C. To render components based on state changes
D. To directly modify the state without any intermediate steps

Solution

  1. Step 1: Understand what actions do

    Actions in Vuex or Vue state management are designed to handle asynchronous tasks or complex logic before changing the state.
  2. Step 2: Differentiate actions from mutations

    Actions do not directly modify state; instead, they commit mutations which then update the state safely.
  3. Final Answer:

    To perform asynchronous operations and then commit mutations to change state -> Option B
  4. Quick Check:

    Actions handle async tasks = D [OK]
Hint: Actions handle async tasks before state changes [OK]
Common Mistakes:
  • Thinking actions directly modify state
  • Confusing actions with mutations
  • Believing actions render UI components
2. Which of the following is the correct syntax to dispatch an action named fetchData in a Vue component?
easy
A. this.$store.dispatch('fetchData')
B. this.dispatch('fetchData')
C. dispatch('fetchData')
D. this.commit('fetchData')

Solution

  1. Step 1: Recall Vuex dispatch syntax

    To call an action, you use this.$store.dispatch('actionName') inside a Vue component.
  2. Step 2: Differentiate dispatch from commit

    commit is used for mutations, not actions. Dispatch is the correct method for actions.
  3. Final Answer:

    this.$store.dispatch('fetchData') -> Option A
  4. Quick Check:

    Dispatch actions via this.$store.dispatch = B [OK]
Hint: Use this.$store.dispatch('actionName') to call actions [OK]
Common Mistakes:
  • Using commit instead of dispatch for actions
  • Calling dispatch without this.$store
  • Trying to dispatch directly without context
3. Given the Vuex store action below, what will be the final state of count after dispatching incrementAsync?
actions: {
  incrementAsync({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
},
mutations: {
  increment(state) {
    state.count++
  }
},
state: {
  count: 0
}
medium
A. count will be 0 immediately and 1 after 1 second
B. count will be 1 immediately
C. count will remain 0 forever
D. count will be 1 immediately and then reset to 0

Solution

  1. Step 1: Understand the asynchronous action

    The action uses setTimeout to delay committing the mutation by 1 second.
  2. Step 2: Trace the state changes

    Initially, count is 0. After 1 second, the increment mutation runs, increasing count to 1.
  3. Final Answer:

    count will be 0 immediately and 1 after 1 second -> Option A
  4. Quick Check:

    Async commit delays state change = A [OK]
Hint: Async actions delay mutations, state updates after delay [OK]
Common Mistakes:
  • Assuming state changes immediately
  • Confusing commit timing with dispatch timing
  • Ignoring asynchronous delay
4. Identify the error in this Vuex action code snippet:
actions: {
  updateName({ commit }, newName) {
    commit('setName', newName)
  }
},
mutations: {
  setName(state, name) {
    state.name = name
  }
},
state: {
  name: ''
}
What is wrong if dispatching updateName does not update the state?
medium
A. The action should use dispatch instead of commit
B. The mutation setName is missing from the store
C. The action is missing the context parameter
D. The action is not properly registered or dispatched

Solution

  1. Step 1: Check action and mutation code

    The action correctly commits the mutation with the new name, and the mutation updates the state.
  2. Step 2: Consider why state doesn't update

    If dispatching the action doesn't update state, likely the action is not properly registered in the store or the dispatch call is incorrect.
  3. Final Answer:

    The action is not properly registered or dispatched -> Option D
  4. Quick Check:

    Unregistered or wrong dispatch causes no state update = A [OK]
Hint: Check action registration and dispatch call if state doesn't update [OK]
Common Mistakes:
  • Using commit inside action is correct, not an error
  • Assuming mutation is missing when it exists
  • Confusing commit and dispatch roles
5. You want to create a Vuex action that fetches user data from an API and updates the state only if the user is active. Which of the following action implementations correctly applies this logic?
hard
A. async fetchUser({ commit }) { const user = await fetch('/api/user').then(res => res.json()) commit('setUser', user) }
B. fetchUser({ commit }) { fetch('/api/user').then(res => res.json()).then(user => { commit('setUser', user) }) }
C. async fetchUser({ commit }) { const user = await fetch('/api/user').then(res => res.json()) if (user.active) commit('setUser', user) }
D. fetchUser({ commit }) { const user = fetch('/api/user').then(res => res.json()) if (user.active) commit('setUser', user) }

Solution

  1. Step 1: Analyze async/await usage

    async fetchUser({ commit }) { const user = await fetch('/api/user').then(res => res.json()) if (user.active) commit('setUser', user) } correctly awaits the fetch call and then checks if the user is active before committing the mutation.
  2. Step 2: Identify issues in other options

    fetchUser({ commit }) { fetch('/api/user').then(res => res.json()).then(user => { commit('setUser', user) }) } commits without checking active status. async fetchUser({ commit }) { const user = await fetch('/api/user').then(res => res.json()) commit('setUser', user) } commits without condition. fetchUser({ commit }) { const user = fetch('/api/user').then(res => res.json()) if (user.active) commit('setUser', user) } does not await fetch, so user is a Promise, causing errors.
  3. Final Answer:

    async fetchUser({ commit }) { const user = await fetch('/api/user').then(res => res.json()) if (user.active) commit('setUser', user) } -> Option C
  4. Quick Check:

    Await fetch and check condition before commit = C [OK]
Hint: Await fetch, check condition, then commit mutation [OK]
Common Mistakes:
  • Not awaiting fetch causing Promise errors
  • Committing without condition check
  • Using then without proper chaining or condition
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