Mateusz Kawka
Mateusz Kawka

Reputation: 422

Strange behavior vuex mutation

Vue/vuex

Hello, i have state like this:

 state: {
            tasks: [{
                title: 'Title task one',
                desc: 'Lorem ipsum dolor sit amet consectetur...',
                completed: false,
                id: 31232131312,
            },
            ...
        ],
        ...
        }

mutations:

 addNewTask: (state, task) => state.tasks.push(task),

In the component, I pass such an object

newTask: {
        title: "",
        desc: "",
        completed: false,
        id: Number
      }

next

store.commit("addNewTask", this.newTask);

Everything works, but when i add another task, both tasks looks exactly same

Example:

{ title: 'task 1 ', desc: 'desc 1', completed: false, id: 11111}

next

{ title: 'task 2 ', desc: 'desc 2', completed: false, id: 22222}

and both tasks looks like this:

{ title: 'task 2 ', desc: 'desc 2', completed: false, id: 22222}

Can someone explain me, how ?

Greetings

EDIT:

repo:

https://github.com/MateuszKawka/tasker

Upvotes: 0

Views: 45

Answers (1)

shashwat
shashwat

Reputation: 1002

So, it's generally a bad idea to mutate items directly within Vuex states. Can you try

addNewTask: (state, task) => state.tasks = state.tasks.concat([task])

That will not mutate the array, but change its value, so Vuex can monitor its changes.

EDIT:

I think I figured out the problem. The problem is you're using the same newTask object every time to create a new task.

Just change the command to

store.commit("addNewTask", Object.assign({}, this.newTask));

That'll create a copy of the newTask object, which will fix this issue.

Upvotes: 1

Related Questions