Skip to content

Commit

Permalink
fix(url): preserve reactivity while assigning state from query (#412)
Browse files Browse the repository at this point in the history
  • Loading branch information
brc-dd committed Dec 15, 2023
1 parent 613882a commit 38b4ab5
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions lib/composables/Url.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import isEqual from 'lodash-es/isEqual'
import isPlainObject from 'lodash-es/isPlainObject'
import { watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
Expand Down Expand Up @@ -38,7 +39,7 @@ export function useUrlQuerySync(
flattenState[key] = cast ? cast(value) : value
})

Object.assign(state, unflattenObject(flattenState))
deepAssign(state, unflattenObject(flattenState))
}

async function setQueryFromState() {
Expand All @@ -53,7 +54,7 @@ export function useUrlQuerySync(
const value = flattenState[key]
const initialValue = flattenInitialState[key]

if (value === initialValue) {
if (isEqual(value, initialValue)) {
delete flattenQuery[key]
} else {
flattenQuery[key] = value
Expand Down Expand Up @@ -94,3 +95,25 @@ function unflattenObject(obj: Record<string, any>) {
return acc
}, {} as Record<string, any>)
}

function deepAssign(target: Record<string, any>, source: Record<string, any>) {
const dest = target
const src = source

if (isPlainObject(src)) {
Object.keys(src).forEach((key) => deepAssignBase(dest, src, key))
} else if (Array.isArray(src)) {
dest.length = src.length
src.forEach((_, key) => deepAssignBase(dest, src, key))
} else {
throw new TypeError('[deepAssign] src must be an object or array')
}
}

function deepAssignBase(dest: Record<string, any>, src: Record<string, any>, key: string | number) {
if (typeof src[key] === 'object' && src[key] !== null) {
deepAssign(dest[key], src[key])
} else {
dest[key] = src[key]
}
}

0 comments on commit 38b4ab5

Please sign in to comment.