Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VUEX: Why can't we affect the whole state object?

Tags:

vuex

I have a RESET mutation in my store that reset the state object to its default value : the solution I found is to Object.assign(state, defaultState) to make it works instead of state = defaultState. Affecting with = on a specific property works but not for the whole state Object.

Work :

RESET: (state) => {
  Object.assign(state, defaultState);
}

Don't work :

RESET: (state) => {
  state = defaultState;
}
like image 439
Pierre Clocher Avatar asked Dec 18 '17 14:12

Pierre Clocher


1 Answers

This is due to the way js works. When you set a new object with = it's a totally new object with a new address in memory, so vuex no longer knows how to track it.

When you use Object.assign(state, defaultState);, it's essentially keeps the same object and it just sets the properties to the new values.

like image 88
Tomer Avatar answered Oct 18 '22 07:10

Tomer