1

For some reason I can not find a working solution to toggle checkbox of an item from Vuex state array. I got it working to a point where I am able to display todo items, but whenever I try to commit and call a toggle mutation, it doesn't work as expected, nothing changes. If I set done = true, it works, but not toggling it. Any idea?

View:

<template>
  <div class="todos">
    <ul>
      <li v-for="todo in $store.state.todos" :key="todo.id">
        <input
          type="checkbox"
          v-model="todo.done"
          @change="$store.commit('toggle', todo.id)"
        />
        <h3>{{ todo.title }}</h3>
      </li>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({});
</script>

<style></style>

State:

import { createStore } from 'vuex';
import Todo from '@/types/Todo';
import { State } from 'vue';

const store = createStore({
  state() {
    return {
      todos: [] as Todo[],
    };
  },
  mutations: {
    add(state: State, todo: Todo) {
      state.todos.push(todo);
    },
    toggle(state: State, todoId: number) {
      const index = state.todos.findIndex((todo) => todo.id === todoId);
      state.todos[index].done = !state.todos[index].done;
    },
  },
});

export default store;

1 Answer 1

1

Try updating the memory reference of the todos array by cloning the state.todos array and deconstructing the todo object.

state.todos = state.todos.map((todo) => ({...todo, done: todoId === todo.id ? !todo.done : todo.done }));
Sign up to request clarification or add additional context in comments.

3 Comments

Seems to be no difference.
@ŽanFras I edited, maybe because the todo was an object as well it should update its memory reference.
Ur welcome, by the way I think the v-model is not necesary since you are updating the value in the store and not in the component, v-model tries to update the value. It should work just by adding value="todo.done" and the @change should do the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.