react-use-websocket icon indicating copy to clipboard operation
react-use-websocket copied to clipboard

Question: How to use with redux-saga

Open MetaBenji opened this issue 1 year ago • 1 comments

@robtaussig I love the library you built and how it handles a lot of the additional work of reconnecting, etc.

We use redux-saga extensively in our application for side effects and I'd love to implement websockets in redux-saga without having to build all of the great features you've already built from scratch. I know your library is hook based but wanted to ask if there is a way to use the existing APIs to make it work with redux-saga.

MetaBenji avatar Feb 24 '24 16:02 MetaBenji

Hi @MetaBenji, Unfortunately, I do not have a lot of experience with redux-saga. Based on my limited understanding of it, I would consider creating a wrapper hook for useWebSocket that acts as an intermediary. Something like:

export const useReduxSagaWebSocket = <T = unknown>(
  url: string | (() => string | Promise<string>) | null,
  options: Options = DEFAULT_OPTIONS,
  connect: boolean = true,
): WebSocketHook<T> => {
  const dispatch = useDispatch();

  return useWebSocket(url, {
    ...options,
    onMessage: (event) => {
      options.onMessage?.(event);
      dispatch({ type: 'MESSAGE_RECEIVED', payload: { event, url } });
    },
    onClose: (event) => {
      options.onClose?.(event);
      dispatch({ type: 'CONNECTION_CLOSED', payload: { event, url } });
    },
    onOpen: (event) => {
      options.onOpen?.(event);
      dispatch({ type: 'CONNECTION_OPENED', payload: { event, url } });
    },
    onError: (event) => {
      options.onError?.(event);
      dispatch({ type: 'CONNECTION_ERROR', payload: { event, url } });
    },
  }, connect);
};

Then you can watch for those events in your sagas and do whatever you need to do to update your store/perform side-effects, etc. Again, I have very limited experience with redux-saga (I've only worked in a codebase where we were removing it), so take my suggestion with a grain of salt!

robtaussig avatar Feb 28 '24 19:02 robtaussig