Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Help with transitioning from different library #44

Open
texas697 opened this issue Jun 24, 2022 · 0 comments
Open

Help with transitioning from different library #44

texas697 opened this issue Jun 24, 2022 · 0 comments

Comments

@texas697
Copy link

I am having a hard time coming from react-use-websocket. Do I need to keep this connection open as I am doing previously? Or is that where the async part comes into play? I am not sure on how to do this. It would be great if someone could help me transition my logic to use this library.

`
import useWebSocket, { ReadyState } from 'react-use-websocket';

const SOCKET_URL = '';

let timestamp = new Date().getTime();
const UseWebSocket = ({ webSocketRef }: { webSocketRef: any }) => {
  webSocketRef.current = useWebSocket(SOCKET_URL, {
    retryOnError: true,
    reconnectInterval: 100000,
  });

  const { sendJsonMessage, lastJsonMessage, readyState } = webSocketRef.current;
  const data = useSelector(getEditForecastJSONSelector);

  const prevData = React.useRef<any>();

  const dispatch = useDispatch();

  const onSetDataReceived = (response: any) => {
    const currentTimestamp = new Date().getTime();
    const diff = currentTimestamp - timestamp;
    if (diff > 200) {
      dispatch(actions.onForeCastDataReceived(response));
      dispatch(actions.onIsLoading(false));
      timestamp = new Date().getTime();
    }
  };

  React.useEffect(() => {
    if (readyState === ReadyState.OPEN) {
      if (!isEqual(prevData.current, data) && data.length > 0) {
        data.forEach((item) => {
          if (item.data) {
            item.data.forEach((x) => {
              x.forecasts.forEach((f) => {
                const payload: SocketPayload = getSocketPayload({ item, f });
                sendJsonMessage(payload, false);
              });
            });
          }
        });
      }
      prevData.current = data;
    }
  }, [
    dispatch,
    data,
    sendJsonMessage,
    readyState,
  ]);

  React.useEffect(() => {
    if (lastJsonMessage !== null) {
      onSetDataReceived(lastJsonMessage);
    } else dispatch(actions.onIsLoading(false));
  }, [lastJsonMessage, onSetDataReceived]);

  return webSocketRef.current;
};

export default UseWebSocket;
`

Current Logic I am trying to get to work.

`const SOCKET_URL = '';

let timestamp = new Date().getTime();
const UseWebSocket = ({ webSocketRef }: { webSocketRef: any }) => {
  webSocketRef.current = new WebSocketAsPromised(SOCKET_URL, {
    packMessage: data => JSON.stringify(data),
    unpackMessage: data => JSON.parse(String(data)),
  });

  const data = useSelector(getEditForecastJSONSelector);

  const prevData = React.useRef<any>();

  const dispatch = useDispatch();

  const onSetDataReceived = (response: any) => {
    const currentTimestamp = new Date().getTime();
    const diff = currentTimestamp - timestamp;
    if (diff > 200) {
      dispatch(actions.onForeCastDataReceived(response));
      dispatch(actions.onIsLoading(false));
      timestamp = new Date().getTime();
    }
  };

  React.useEffect(() => {
    // (async () => {
    //   try {
    //     await webSocketRef.current.open();
    //   } catch (e) {
    //     console.error(e);
    //   }
    // })();
  }, []);

  React.useEffect(() => {
    const run = async () => {
      if (!isEqual(prevData.current, data) && data.length > 0) {
        for (const item of data) {
          if (item.data) {
            for (const x of item.data) {
              for (const f of x.forecasts) {
                const payload: SocketPayload = getSocketPayload({ item, f });
                try {
                  webSocketRef.current.onError.addListener((event: any) => console.error(event));
                  webSocketRef.current.onUnpackedMessage.addListener((res: any) => {
                    console.log(res);
                    onSetDataReceived(res);
                  });
                  await webSocketRef.current.open();
                  await webSocketRef.current.sendPacked(payload);
                } catch (e) {
                  console.error(e);
                } finally {
                  // await webSocketRef.current.close();
                }
              }
            }
          }
        }
      }
      prevData.current = data;
    };
    run();
  }, [
    dispatch,
    data,
    onSetDataReceived,
  ]);

  React.useEffect(() => {
    // if (lastJsonMessage !== null) {
    //   onSetDataReceived(lastJsonMessage);
    // } else dispatch(actions.onIsLoading(false));
  }, [onSetDataReceived]);

  return webSocketRef.current;
};

export default UseWebSocket;`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant