useLoading.tsx 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { isDef } from '@/utils/is'
  2. import { useDebounceFn } from 'ahooks'
  3. import { useContext, useEffect } from 'react'
  4. import { FlowContext } from '../context'
  5. import { Actions } from '../enum'
  6. type LoadingOptions = {
  7. /** @name 延迟时间 */
  8. delay?: number
  9. }
  10. const useLoading = (opt: LoadingOptions = { delay: 500 }) => {
  11. const { flowState, dispatch } = useContext(FlowContext)
  12. const cancel = () => {
  13. dispatch({
  14. type: Actions.SET_FOLW_PROPS,
  15. payload: {
  16. canvasLoading: false
  17. }
  18. })
  19. }
  20. const { run: resetLoading, cancel: tryCancelDebounceFn } = useDebounceFn(cancel, {
  21. wait: opt.delay
  22. })
  23. useEffect(() => {
  24. return () => tryCancelDebounceFn()
  25. }, [])
  26. const run = () => {
  27. // 若当前loading为true停止执行
  28. if (isDef(flowState.canvasLoading) && flowState.canvasLoading) {
  29. return
  30. }
  31. dispatch({
  32. type: Actions.SET_FOLW_PROPS,
  33. payload: {
  34. canvasLoading: true
  35. }
  36. })
  37. resetLoading()
  38. }
  39. return { run }
  40. }
  41. export default useLoading