React 自定义请求Hook

2021-10-24
import { useState, useEffect, useRef } from 'react'

/**
 * 
 * @param {Promise} request 请求
 * @param {Number} polling 开启轮询
 */
function useRequest (request, polling = 0) {
  const [state, updateState] = useState({
    loading: false,
    error: undefined,
    data: undefined,
  })
  const requestRef = useRef(request)
  const pollingRef = useRef(polling)
  const pollingIdRef = useRef(null)

  useEffect(() => {
    async function fetchRequest () {
      try {
        updateState({ loading: true })
        const resp = await requestRef.current()
        updateState({ loading: false, data: resp })
      } catch (error) {
        updateState({ loading: false, error: error.message })
      }
    }
    
    fetchRequest()
    if (pollingRef.current !== 0) {
      pollingIdRef.current = setInterval(() => {
        fetchRequest()
      }, pollingRef.current)
    }

    return () => {
      pollingIdRef.current && clearInterval(pollingIdRef.current)
    }
  }, [])

  return { ...state, pollingId: pollingIdRef.current }
}

export default useRequest
cd ..