ahooks#useUnmount TypeScript Examples

The following examples show how to use ahooks#useUnmount. 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: config-setting.tsx    From bext with MIT License 6 votes vote down vote up
SchemaEditor: FC = () => {
  const { draft, setDraft } = useDraft();
  const defaultContent = useMemo(
    () => JSON.stringify(draft?.configSchema || {}),
    [],
  );
  const currentContent = useRef(defaultContent);

  useUnmount(() => {
    try {
      setDraft({
        configSchema: JSON.parse(currentContent.current),
        defaultConfig: undefined,
      });
    } catch (error) {}
  });

  const ref = useRef<HTMLIFrameElement>(null);

  useEventListener('message', ({ data }) => {
    switch (data?.type) {
      case 'jse/init':
        ref.current?.contentWindow?.postMessage(
          { type: 'jse/set', payload: defaultContent },
          '*',
        );
        break;
      case 'jse/content':
        currentContent.current = data.payload;
        break;
      default:
        break;
    }
  });

  return <iframe src={config.jse} ref={ref} className="w-full h-full" />;
}
Example #2
Source File: useWebSocket.tsx    From ui with MIT License 4 votes vote down vote up
export default function useWebSocket(
  socketUrl: string,
  options: Options = {},
): Result {
  const {
    reconnectLimit = 3,
    reconnectInterval = 3 * 1000,
    manual = false,
    onOpen,
    onClose,
    onMessage,
    onError,
    protocols,
  } = options;

  const onOpenRef = useLatest(onOpen);
  const onCloseRef = useLatest(onClose);
  const onMessageRef = useLatest(onMessage);
  const onErrorRef = useLatest(onError);

  const reconnectTimesRef = useRef(0);
  const reconnectTimerRef = useRef<ReturnType<typeof setTimeout>>();
  const websocketRef = useRef<WebSocket>();

  const unmountedRef = useRef(false);

  const [latestMessage, setLatestMessage] = useState<
    WebSocketEventMap['message']
  >();
  const [readyState, setReadyState] = useState<ReadyState>(ReadyState.Closed);

  const reconnect = () => {
    if (
      reconnectTimesRef.current < reconnectLimit &&
      websocketRef.current?.readyState !== ReadyState.Open
    ) {
      if (reconnectTimerRef.current) {
        clearTimeout(reconnectTimerRef.current);
      }

      reconnectTimerRef.current = setTimeout(() => {
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        connectWs();
        reconnectTimesRef.current++;
      }, reconnectInterval);
    }
  };

  const connectWs = () => {
    if (reconnectTimerRef.current) {
      clearTimeout(reconnectTimerRef.current);
    }

    if (websocketRef.current) {
      websocketRef.current?.close();
    }

    websocketRef.current = new (getPlatform === 'wechat'
      ? (wx as any).WebSocket
      : WebSocket)(socketUrl, protocols);
    setReadyState(ReadyState.Connecting);

    if (!websocketRef.current) {
      return;
    }
    websocketRef.current.onerror = event => {
      if (unmountedRef.current) {
        return;
      }
      reconnect();
      onErrorRef.current?.(event);
      setReadyState(websocketRef.current?.readyState || ReadyState.Closed);
    };

    websocketRef.current.onopen = event => {
      if (unmountedRef.current) {
        return;
      }
      onOpenRef.current?.(event);
      reconnectTimesRef.current = 0;
      setReadyState(websocketRef.current?.readyState || ReadyState.Open);
    };

    websocketRef.current.onmessage = (
      message: WebSocketEventMap['message'],
    ) => {
      if (unmountedRef.current) {
        return;
      }
      onMessageRef.current?.(message);
      setLatestMessage(message);
    };

    websocketRef.current.onclose = event => {
      if (unmountedRef.current) {
        return;
      }
      reconnect();
      onCloseRef.current?.(event);
      setReadyState(websocketRef.current?.readyState || ReadyState.Closed);
    };
  };

  const sendMessage: WebSocket['send'] = (message: any) => {
    if (readyState === ReadyState.Open) {
      websocketRef.current?.send(message);
    } else {
      throw new Error('WebSocket disconnected');
    }
  };

  const connect = () => {
    reconnectTimesRef.current = 0;
    connectWs();
  };

  const disconnect = () => {
    if (reconnectTimerRef.current) {
      clearTimeout(reconnectTimerRef.current);
    }

    reconnectTimesRef.current = reconnectLimit;
    websocketRef.current?.close();
  };

  useEffect(() => {
    if (!manual) {
      connect();
    }
  }, [socketUrl, manual]);

  useUnmount(() => {
    unmountedRef.current = true;
    disconnect();
  });

  return {
    latestMessage,
    sendMessage: useMemoizedFn(sendMessage),
    connect: useMemoizedFn(connect),
    disconnect: useMemoizedFn(disconnect),
    readyState,
    webSocketIns: websocketRef.current,
  };
}