react-use#useThrottleFn TypeScript Examples

The following examples show how to use react-use#useThrottleFn. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransactionGasProvider.tsx    From mStable-apps with GNU Lesser General Public License v3.0 5 votes vote down vote up
TransactionGasProvider: FC<{ id: string }> = ({ children, id }) => {
  const { [id]: transaction } = useTransactionsState()
  const { protocolName } = useNetwork()
  const [estimationError, setEstimationError] = useState<string | undefined>()
  const [gasLimit, setGasLimit] = useState<BigNumber | undefined>()
  const [gasPrice, setGasPrice] = useState<number | undefined>()
  const nativeToken = useNativeToken()

  // +100% for Polygon, +10% otherwise
  const gasMargin = protocolName === Networks.Polygon ? 10000 : 1000

  useThrottleFn<Promise<void>, [Transaction | undefined]>(
    async _transaction => {
      let estimate: BigNumber | undefined
      if (_transaction) {
        try {
          estimate = await _transaction.manifest.estimate(gasMargin)
        } catch (error) {
          // MetaMask error messages are in a `data` property
          const txMessage = error.data?.message || error.message
          setEstimationError(txMessage)
          console.error(error)
        }
      }
      setGasLimit(estimate)
    },
    5000,
    [transaction],
  )

  const insufficientBalance = gasLimit && gasPrice && nativeToken?.balance ? nativeToken.balance.exact.lt(gasLimit.mul(gasPrice)) : false

  return (
    <ctx.Provider
      value={useMemo(
        () => ({ estimationError, gasLimit, gasPrice, setGasPrice, insufficientBalance }),
        [estimationError, gasLimit, gasPrice, setGasPrice, insufficientBalance],
      )}
    >
      {children}
    </ctx.Provider>
  )
}
Example #2
Source File: debug.tsx    From erda-ui with GNU Affero General Public License v3.0 4 votes vote down vote up
DebugConfigPage = () => {
  const pageRef = React.useRef(null);
  const cacheData = window.localStorage.getItem('config-page-debug');
  const [text, setText] = React.useState(cacheData || defaultJson);
  const [logs, setLogs] = React.useState<ILog[]>([]);
  const [showCode, setShowCode] = React.useState(true);
  const [showLog, setShowLog] = React.useState(false);
  const [importValue, setImportValue] = React.useState('');
  const [activeLog, setActiveLog] = React.useState(0);
  const { url, scenario, debug, ...restQuery } = routeInfoStore.useStore((s) => s.query);
  const [proxyApi, setProxyApi] = React.useState(url);
  const _defaultData = scenario
    ? {
        scenario: {
          scenarioKey: scenario,
          scenarioType: scenario,
        },
        inParams: restQuery,
      }
    : defaultData;
  const [config, setConfig] = React.useState(_defaultData);

  useThrottleFn<string, any>(
    (newText) => {
      window.localStorage.setItem('config-page-debug', newText);
      return newText;
    },
    5000,
    [text],
  );

  useUpdateEffect(() => {
    if (activeLog) {
      setConfig(logs?.[activeLog - 1]?.pageData);
    }
  }, [activeLog]);

  const getMock = React.useCallback(
    (payload: any) => {
      return agent
        .post(proxyApi)
        .send(payload)
        .then((response: any) => {
          return response.body.protocol ? response.body : response.body.data;
        });
    },
    [proxyApi],
  );

  if (!debug) {
    return <DiceConfigPage scenarioType={scenario} scenarioKey={scenario} inParams={restQuery} />;
  }

  const updateMock = (_text?: string) => {
    try {
      const obj = new Function(`return ${_text || text}`)();
      setConfig(obj);
    } catch (error) {
      message.error('内容有错误');
    }
  };

  const onExecOp = ({ cId, op, reload, updateInfo, pageData }: any) => {
    setLogs((prev) => {
      const reLogs = prev.concat({
        time: moment().format('HH:mm:ss'),
        type: '操作',
        cId,
        opKey: op.text || op.key,
        command: JSON.stringify(op.command, null, 2),
        reload,
        data: JSON.stringify(updateInfo, null, 2),
        pageData,
      });
      setActiveLog(reLogs.length);
      return reLogs;
    });
  };

  const exportLog = () => {
    const reLogs = logs.map((item) => {
      const { assertList, ...rest } = item;
      const _asserts = assertList?.filter((aItem) => {
        return aItem.key && aItem.operator && aItem.value;
      });
      return { ...rest, assertList: _asserts };
    });
    const blob = new Blob([JSON.stringify(reLogs, null, 2)], { type: 'application/vnd.ms-excel;charset=utf-8' });
    const fileName = `assert-log.txt`;
    const objectUrl = URL.createObjectURL(blob);
    const downloadLink = document.createElement('a');
    downloadLink.href = objectUrl;
    downloadLink.setAttribute('download', fileName);
    document.body.appendChild(downloadLink);
    downloadLink.click();
    window.URL.revokeObjectURL(downloadLink.href);
  };

  const importLog = () => {
    try {
      const obj = new Function(`return ${importValue}`)();
      setLogs(obj || []);
      setActiveLog((obj || []).length);
    } catch (error) {
      message.error('内容有错误');
    }
  };

  return (
    <div className="h-full debug-page-container flex flex-col ml-4">
      <div className="flex justify-between mb-1 item-center">
        <div className="w-52">
          <Checkbox checked={showCode} onChange={(e) => setShowCode(e.target.checked)}>
            代码
          </Checkbox>
          <Checkbox className="ml-2" checked={showLog} onChange={(e) => setShowLog(e.target.checked)}>
            日志
          </Checkbox>
        </div>
        <Input value={proxyApi} size="small" onChange={(e) => setProxyApi(e.target.value)} />
      </div>
      <div className="debug-page flex-1 h-0 flex justify-between items-center">
        <div className={`flex flex-col left h-full  ${showCode || showLog ? '' : 'hide-left'}`}>
          {showCode ? (
            <div className="flex-1">
              <FileEditor
                autoHeight
                fileExtension="json"
                valueLimit={false}
                value={text}
                onChange={(_text) => {
                  setText(_text);
                  updateMock(_text);
                }}
              />
              <Button type="primary" className="update-button" onClick={() => updateMock()}>
                更新
              </Button>
              <Button
                type="primary"
                className="request-button"
                onClick={() => {
                  pageRef.current.reload(config);
                }}
              >
                请求
              </Button>
            </div>
          ) : null}
          {showLog ? (
            <div className={`log-panel mt-2`}>
              <h3>
                操作日志
                <span
                  className="ml-2 fake-link"
                  onClick={() => {
                    setLogs([]);
                    setActiveLog(0);
                  }}
                >
                  清空
                </span>
                <span className="ml-2 fake-link" onClick={exportLog}>
                  导出
                </span>
                <Tooltip
                  overlayStyle={{ width: 400, maxWidth: 400 }}
                  title={
                    <div>
                      <Input.TextArea value={importValue} onChange={(e) => setImportValue(e.target.value)} />
                      <Button size="small" type="primary" onClick={importLog}>
                        导入
                      </Button>
                    </div>
                  }
                >
                  <span className="ml-2 fake-link" onClick={importLog}>
                    导入
                  </span>
                </Tooltip>
              </h3>
              {logs.map((log, i) => {
                return (
                  <LogItem
                    key={i}
                    index={i + 1}
                    activeLog={activeLog}
                    setActiveLog={(l) => setActiveLog(l)}
                    log={log}
                    setLog={(_log) => setLogs((prev) => prev.map((item, idx) => (idx === i ? _log : item)))}
                  />
                );
              })}
            </div>
          ) : null}
        </div>
        <div className={`right overflow-auto h-full ${showCode || showLog ? '' : 'full-right'}`}>
          <ErrorBoundary>
            <DiceConfigPage
              ref={pageRef}
              showLoading
              scenarioType={scenario || config?.scenario?.scenarioType}
              scenarioKey={scenario || config?.scenario?.scenarioKey}
              inParams={config?.inParams}
              debugConfig={config}
              onExecOp={onExecOp}
              useMock={getMock}
              forceMock={!!proxyApi}
              updateConfig={(v) => {
                setConfig(v);
                setText(JSON.stringify(v, null, 2));
              }}
            />
          </ErrorBoundary>
        </div>
      </div>
    </div>
  );
}