What is WebSockets

WebSockets have brought a robust socket communication method directly into our browsers.

What started as a solution for polling data changes on the server is slowly taking over more and more responsibilities from traditional REST endpoints.The action-based architecture of Redux makes working with WebSockets exceptionally easy and natural, as it involves using WebSockets as a pipe to pass actions to and from the server.

Architecture Of WebSockets

WebSockets allow us to open a connection to a server and send or receive messages in a fully asynchronous way.

onopen – A connection has become active.
onclose – A connection has been closed.
onerror – An error related to WebSocket communication has been raised.
onmessage – A new message has been received.

onopen:-
This is mainly an informative stage; we need to indicate to ourselves that the socket is ready to send and receive data and might choose to notify the rest of the Redux application that the socket is ready (perhaps to show some indication in the UI).

Once the socket is open, we dispatch a simple { type: ‘WS_CONNECTED’ } action to notify the rest of Redux:

Handling onopen


websocket.onopen = () => dispatch(wsConnected());


The wsConnected() function is a simple action creator that should be implemented in one of the action creator files:


app/actions/ui.js


import { WS_CONNECTED } from 'consts/action-types';

const wsConnected = () => ({ type: WS_CONNECTED });

onerror:-

In this example we will stop at a generic console.log() and leave it to the reader to consider more advanced error handling methods:

Handling onclose

 Websocket.onerror = (error) =>

console.log("WS Error", error.data);

onmessage


This callback is called every time a new message is received over a WebSocket. If we have built our server to be fully compatible with Redux actions, the message can simply be dispatched to the store.

Handling onmessage

 websocket.onmessage = (event) => dispatch(JSON.parse(event.data));

If you like this post, don’t forget to share 🙂

This article is written by our awesome writer
Comments to: Usage of WebSockets In Redux

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Join our Newsletter

Get our monthly recap with the latest news, articles and resources.

By subscribing you agree to our Privacy Policy.

Latest Articles

Explore Tutorials By Categories

About

Codeverb is simply an all in one interactive learning portal, we regularly add new topics and keep improving the existing ones, if you have any suggestions, questions, bugs issue or any other queries you can simply reach us via the contact page

Login

Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
  •  
    Strength indicator
  •  
  •  
    Log In | Lost Password