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

Question: How to use with redux-saga #229

Open
MetaBenji opened this issue Feb 24, 2024 · 1 comment
Open

Question: How to use with redux-saga #229

MetaBenji opened this issue Feb 24, 2024 · 1 comment

Comments

@MetaBenji
Copy link

@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.

@robtaussig
Copy link
Owner

robtaussig commented Feb 28, 2024

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!

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

2 participants