zoukankan      html  css  js  c++  java
  • [React] useAsync

    const defaultInitialState = {status: 'idle', data: null, error: null}
    export function useAsync(initialState) {
      const initialStateRef = React.useRef({
        ...defaultInitialState,
        ...initialState,
      })
      const [{status, data, error}, setState] = React.useReducer(
        (s, a) => ({...s, ...a}),
        initialStateRef.current,
      )
    
      const safeSetState = useSafeDispatch(setState)
    
      const run = React.useCallback(
        promise => {
          if (!promise || !promise.then) {
            throw new Error(
              `The argument passed to useAsync().run must be a promise. Maybe a function that's passed isn't returning anything?`,
            )
          }
          safeSetState({status: 'pending'})
          return promise.then(
            data => {
              safeSetState({data, status: 'resolved'})
              return data
            },
            error => {
              safeSetState({status: 'rejected', error})
              return error
            },
          )
        },
        [safeSetState],
      )
    
      const setData = React.useCallback(data => safeSetState({data}), [
        safeSetState,
      ])
      const setError = React.useCallback(error => safeSetState({error}), [
        safeSetState,
      ])
      const reset = React.useCallback(() => safeSetState(initialStateRef.current), [
        safeSetState,
      ])
    
      return {
        // using the same names that react-query uses for convenience
        isIdle: status === 'idle',
        isLoading: status === 'pending',
        isError: status === 'rejected',
        isSuccess: status === 'resolved',
    
        setData,
        setError,
        error,
        status,
        data,
        run,
        reset,
      }
    }

    Using:

      const {data: items, run} = useAsync({data: [], status: 'pending'})
      React.useEffect(() => {
        run(getItems(inputValue))
      }, [inputValue, run])
  • 相关阅读:
    JavaSE教程-01初识Java-思维导图
    theano 模块 MLP示例
    EM理解(转)
    交叉验证(Cross Validation)方法思想简介
    imfilter()用法
    PSNR
    conv2、filter2、imfilter的区别
    图像上采样(图像插值)增取样(Upsampling)或内插(Interpolating)下采样(降采样),
    CSS清除浮动大全共8种方法
    支付宝轮播
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13861838.html
Copyright © 2011-2022 走看看