use-scope-value-setter-only.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import {
  2. type Dispatch,
  3. type SetStateAction,
  4. useCallback,
  5. useState,
  6. } from 'react'
  7. import { useIdeContext } from '../context/ide-context'
  8. import _ from 'lodash'
  9. /**
  10. * Similar to `useScopeValue`, but instead of creating a two-way binding, only
  11. * changes in react-> angular direction are propagated, with `value` remaining
  12. * local and independent of its value in the Angular scope.
  13. *
  14. * The interface is compatible with React.useState(), including
  15. * the option of passing a function to the setter.
  16. */
  17. export default function useScopeValueSetterOnly<T = any>(
  18. path: string, // dot '.' path of a property in the Angular scope.
  19. defaultValue?: T
  20. ): [T | undefined, Dispatch<SetStateAction<T | undefined>>] {
  21. const { $scope } = useIdeContext()
  22. const [value, setValue] = useState<T | undefined>(defaultValue)
  23. const scopeSetter = useCallback(
  24. (newValue: SetStateAction<T | undefined>) => {
  25. setValue(val => {
  26. const actualNewValue = _.isFunction(newValue) ? newValue(val) : newValue
  27. $scope.$applyAsync(() => _.set($scope, path, actualNewValue))
  28. return actualNewValue
  29. })
  30. },
  31. [path, $scope]
  32. )
  33. return [value, scopeSetter]
  34. }