ahooks#useThrottleEffect TypeScript Examples

The following examples show how to use ahooks#useThrottleEffect. 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: draft.ts    From bext with MIT License 4 votes vote down vote up
[DraftProvider, useDraft] = constate(() => {
  const [cacheDraft, setCacheDraft] = useLocalStorageState<Draft>(
    BEXT_DRAFT_KEY,
    { defaultValue: null },
  );

  const [draft, setDraftObject, getDraftObject] =
    useGetState<Draft>(cacheDraft);

  const setDraft = useCallback(
    (state: Draft) =>
      setDraftObject((prev) =>
        state === null
          ? null
          : {
              ...prev,
              ...state,
              // FIXME: 清理存量数据
              build: undefined,
              options: undefined,
            },
      ),
    [],
  );

  const [clientReady, setClientReady, getClientReady] = useGetState(false);

  const injectDraft = useMemoizedFn((content: string = '{}') => {
    try {
      setDraftObject(JSON.parse(content));
      setClientReady(true);
    } catch (error) {}
  });

  useEffect(() => ((window.injectDraft = injectDraft), void 0));

  useEffect(() => {
    if (isBextClient) {
      try {
        window.ReactNativeWebView?.postMessage(
          JSON.stringify({
            type: 'ready',
          }),
        );
      } catch (error) {}
    }
  }, [isBextClient]);

  const saveDraft = useMemoizedFn(() => {
    setCacheDraft(draft);
    if (isBextClient && getClientReady()) {
      try {
        window.ReactNativeWebView?.postMessage(
          JSON.stringify({
            type: 'save',
            payload: draft,
          }),
        );
      } catch (error) {}
    }
  });

  useThrottleEffect(
    () => {
      if (draft) {
        saveDraft();
      }
    },
    [draft],
    { wait: 3000 },
  );

  return {
    draft,
    setDraft,
    setDraftObject,
    getDraftObject,
    saveDraft,
    cacheDraft,
  };
})