Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(syncRef): avoid infinite sync #3312

Merged
merged 5 commits into from
Aug 25, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 4 additions & 4 deletions packages/shared/syncRef/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,26 +51,26 @@ describe('syncRef', () => {

it('works with mutual convertors', () => {
const left = ref(10)
const right = ref(1)
const right = ref(2)

syncRef(left, right, {
transform: {
ltr: left => left * 2,
rtl: right => Math.round(right / 2),
rtl: right => Math.floor(right / 3),
},
})

// check immediately sync
expect(right.value).toBe(20)
expect(left.value).toBe(10)
expect(left.value).toBe(6)

left.value = 30
expect(right.value).toBe(60)
expect(left.value).toBe(30)

right.value = 10
expect(right.value).toBe(10)
expect(left.value).toBe(5)
expect(left.value).toBe(3)
})

it('works with only rtl convertor', () => {
Expand Down
20 changes: 18 additions & 2 deletions packages/shared/syncRef/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,21 +50,37 @@ export function syncRef<L, R = L>(left: Ref<L>, right: Ref<R>, options: SyncRefO
let watchLeft: WatchStopHandle
let watchRight: WatchStopHandle

let stop = false

const transformLTR = transform.ltr ?? (v => v)
const transformRTL = transform.rtl ?? (v => v)

if (direction === 'both' || direction === 'ltr') {
watchLeft = watch(
left,
newValue => right.value = transformLTR(newValue) as R,
(newValue) => {
if (stop)
return

stop = true
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the flush paramter of options is 'post', dose it work properly?

right.value = transformLTR(newValue) as R
stop = false
},
{ flush, deep, immediate },
)
}

if (direction === 'both' || direction === 'rtl') {
watchRight = watch(
right,
newValue => left.value = transformRTL(newValue) as L,
(newValue) => {
if (stop)
return

stop = true
left.value = transformRTL(newValue) as L
stop = false
},
{ flush, deep, immediate },
)
}
Expand Down