Skip to content

Commit

Permalink
fix (gabrielmbmb#6): deep clone old state before merging
Browse files Browse the repository at this point in the history
a simple deep clone of the old state prevents setting off
'Error: do not mutate vuex store state outside mutation handlers'
when merging the preset statesPaths
  • Loading branch information
abernh committed Oct 18, 2021
1 parent 1fb073c commit f028348
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,31 @@ export default function(options?: Options) {
return result;
}

function mergeState(oldState: object, newState: object) {
/**
* simple object deep clone method
* @param obj
*/
function cloneObj(obj: any): any {
if (Array.isArray(obj)) {
return obj.map((val) => cloneObj(val));
} else if (typeof obj === 'object') {
return Object.keys(obj).reduce((r: any, key) => {
r[key] = cloneObj(obj[key]);
return r;
}, {});
}
return obj;
}

function mergeState(oldState: any, newState: object) {
// if whole state is to be replaced then do just that
if (statesPaths.length === 0) return { ...newState };
// else take old state
const merged = { ...oldState };

// else clone old state
const merged: any = cloneObj(oldState);

// and replace only specified paths
statesPaths.forEach(statePath => {
statesPaths.forEach((statePath) => {
const newValue = pick(statePath, newState);
// remove value if it doesn't exist, overwrite otherwise
if (typeof newValue === 'undefined') remove(statePath, merged);
Expand Down

0 comments on commit f028348

Please sign in to comment.