You have an application using an Elixir and Phoenix backend, and a TypeScript and React frontend. You’d like to use two-way communication between the frontend and backend over Phoenix’s channels using websockets.
Github alexgriff/use-phoenix-channel provides a good starting point, but it doesn’t quite work in typescript. I’ve taken this and made a few modifications to it:
- Ported to TypeScript.
- It no longer forces you to use a reducer to manage state. You provide a callback when messages are received, state management is up to the caller.
Code listing (
I’ve seen this component kick off a warning in the console in some circumstances. I’ll be keeping an eye out for it and will update the post later when I fix it.
Update 10/28/2019: Updated the component to leave channels when unmounting properly.