A
A
alex4answ2021-01-19 09:01:25
React
alex4answ, 2021-01-19 09:01:25

How to organize work with WebSocket?

Good afternoon, you need to subscribe to WebSocket from different components at different levels.

Where should I connect?

I have 2 options:
1. Use the context by passing the connection
2. Connect in a separate file, and subscribe to updates in the useEffect component.

But I didn’t find any good examples where it’s not a blunder “right now, in useEffect, we’ll quickly set everything up,” I didn’t find.
It is not clear how and where to do error handling, disconnection, etc.

Please tell me, maybe someone has some developments, or I saw high-quality github projects, and not a stump "it works, okay, it will do."

How do they usually organize work with ws, where are connections stored, how are they passed to components, how are disconnections handled?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Osher, 2021-01-19
@alex4answ

Depends on the size of the project and further support. If one-two-spit, then at least through `window.ws = new WebSocket()`. If you already need something more concise, then I would try to isolate the socket connection from the components as much as possible. I would make it so that some context would only pass business methods to components. And he did the work with the socket under the hood, hiding it from the components.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question