Files
headlessui/packages/@headlessui-react/src/hooks/use-watch.ts
T
Jordan Pittman b28d177a95 Fix displayValue syncing problem (#1755)
* ensure `syncInputValue` is updated correctly

* WIP

* WIP

* Don’t resync on open

* Fix react value syncing

update

* Add comment

* Port new setup over to Vue

* Remove `inputPropsRef`

We hardly knew ye

* Remove repro

* Cleanup

* Update changelog

Co-authored-by: Robin Malfait <malfait.robin@gmail.com>
2022-08-10 12:38:30 -04:00

24 lines
700 B
TypeScript

import { useEffect, useRef } from 'react'
import { useEvent } from './use-event'
export function useWatch<T extends any[]>(
cb: (newValues: [...T], oldValues: [...T]) => void | (() => void),
dependencies: [...T]
) {
let track = useRef<typeof dependencies>([] as unknown as [...T])
let action = useEvent(cb)
useEffect(() => {
let oldValues = [...track.current] as unknown as [...T]
for (let [idx, value] of dependencies.entries()) {
if (track.current[idx] !== value) {
// At least 1 item changed
let returnValue = action(dependencies, oldValues)
track.current = dependencies
return returnValue
}
}
}, [action, ...dependencies])
}