I have just had to implement this and found it hard to come across a simple working solution out there.
So here is mine:
Prerequisites
Let’s consider the following WebSocket
object:
const mySocket = new WebSocket("ws://www.xyz.com/socketServer", "protocol"); |
We can listen to incoming messages with
mySocket.onmessage = (message) => { |
and close the websocket with
mySocket.close(); |
Setup redux-saga
To listen recurring events, saga provides an eventChannel object.
Basic usage
// 1- Create a channel that listens to messages from the server |
Once the channel is created (we will get there in a second), we can use yield take(channel)
to listen to the message received. By putting that call in a while(true) {...}
loop we can be listening to messages forever.
Create the Event Channel
The eventChannel takes a callback parameter with an emit argument to put messages onto the eventChannel
. This callback function should return another function to be executed when the connection is closed.
function createEventChannel (socket) { |
Plug in that function in the example above and you are ready to go.
Full Working Example
// mySaga.js |
Hope that helps !