Utilizing Socket technology in combination with Sails JS and React JS

Currently, I have a live bidding system in place. On the bidding page, we display both the base price and current bid price of an item. Whenever a user updates the price of an item, I would like that new price to automatically reflect for all customers who have the bidding page open, without requiring a page reload.

My goal is to send a message from the server to the client side whenever a user updates the price of an item. Upon receiving this message on the client side, the table data should be updated accordingly.

config/socket

transports: ['polling', 'websocket'],

Server Side - BidUpdateController [http://localhost:7039]

sails.io.on("connection", (socket) => {
   console.log("SOCKET ID : "+socket.id);
   sails.sockets.broadcast('bidUpdate',{ greeting: 'UPDATED!' });
   socket.on('disconnect', () => { // Do we need this..?
     console.log('User disconnected');
   });
})

The above code allows me to track the socket id in my console: SOCKET ID : wjMGczPrXtx5UpOrBBN3

Client Side - React Bid List Page [http://localhost:3637]

import io from 'socket.io-client';
React.useEffect(() => {
    let connectionOptions =  {
      "force new connection" : true,
      "reconnectionAttempts":"Infinity",
      "timeout" : 20000,
      "transports" : ['polling', 'websocket']
    };
    
    const socket = io.connect('http://localhost:7039',connectionOptions);
    console.log("SOCKET CONNECTION : "+socket.connected); // This returns False
    
    socket.on('bidUpdate', (data) => { // This part does not pertain  
      console.log("Response"+ data.greeting);
      // Upon receiving data, I will call a function to update the table data..
    });
      return () => {
      socket.disconnect();
      }
 },[])

The provided code displays information as follows: React Page Console

I am currently following tutorials and am unsure of the exact concept behind this functionality. Any assistance or guidance would be greatly appreciated!

Answer №1

Before initiating broadcast functionality, ensure you have joined the room using sails.sockets.join(). To send a message to all sockets without being in a specific room, utilize sails.sockets.blast(). Access documentation here

In BidUpdateController, you can easily

sails.sockets.blast('bidUpdate',{ greeting: 'UPDATED!' });

In the React Bid List page

import socketIOClient from "socket.io-client";
import sailsIOClient from "sails.io.js";

React.useEffect(() => {
  // Initialize the io socket
  let io;
  if (socketIOClient.sails) {
    io = socketIOClient;
  } else {
    io = sailsIOClient(socketIOClient);
  }

  io.sails.url = "http://localhost:7039"; // Specify the server URL

  io.socket.on("connect", function onConnect() {
    console.log("Connection established with Sails server!");
  });

  const bidUpdateHandler = (data) => {
    console.log("Response received: " + data.greeting);
  };

  // Register the 'bidUpdate' event listener
  io.socket.on('bidUpdate', bidUpdateHandler);

  // Remove the event listener upon unmounting the component
  return () => {
    io.socket.off('bidUpdate', bidUpdateHandler);
  };
}, []);

If the socket successfully connects to the server, you will see this displayed in the console.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we ensure that the Material-UI <Select> component is as wide as the widest <MenuItem>?

I am attempting to adjust a Mui Select field so that it is the same width as its largest MenuItem. Despite trying to utilize the autoWidth prop on the Select component, I have not been able to achieve the desired result. To better illustrate the issue, I h ...

When the email field is changed, the string is not being set to the state if it is

I encountered a strange issue while setting an email input as a string to state. Even though I can see on React Dev Tools that it gets sent, when I try to log it from another function, I get an empty string. The odd part is, if I change the order of the in ...

Accessing information from Firebase database through react native technology

Is there a way to retrieve data as a string? retrieveDataAsString() { firebase.database().ref('users/USER_UID/username').on('value', snap => snap.val()) } console.log(this.retrieveDataAsString()) Why does the output show undefi ...

The retrieved item has not been linked to the React state

After successfully fetching data on an object, I am attempting to assign it to the state variable movie. However, when I log it to the console, it shows as undefined. import React, {useState, useEffect} from "react"; import Topbar from '../H ...

Surprising Outcome from Applying nextjs with useState and useRef Together

Currently, I am a beginner at learning Next.js and I am working on a small project that includes login functionality and a navigation bar. The code snippet below outlines my approach. Initially, I fetch the user token from my local backend, store it in loc ...

What is the best way to completely uninstall Froala editor from your system?

As a beginner with the froala editor, I am looking for a solution to remove all previous instances created for the editor. Is there a way to completely destroy all instances of the froala editor? Please assist me with my requirement. Thank you in advance ...

Error: The specified module cannot be found. The client package path is not exported from the package

I've encountered an issue while using Next.js and NextAuth with Nginx. My build is failing, and I'm unsure of how to resolve this specific error. 2021-12-06T09:35:02.4779281Z https://nextjs.org/telemetry 2021-12-06T09:35:02.4779648Z 2021-12-06T ...

"Receiving data from an axios call in React using useEffect leads to an error message: "Property 'numero' cannot be read as undefined"

I am encountering an issue while trying to fetch a mock API using axios. Setting up the useEffect hook to fetch the API data const FetchMockAPI = () => { const [data, setData] = useState(); useEffect(() => { ...

Utilize a proxy for "localhost" within a React project on Codesandbox.io

I am looking to integrate Spring Boot REST services from my local computer into a React project on codesandbox.io. In order to do this, I have modified my package.json file in my local system by adding the following line: "proxy": "http://localhost:8080/" ...

Tips for troubleshooting issues with create-react-app

npm ERR! errno ERR_SOCKET_TIMEOUT npm ERR! network Invalid response body received when attempting to download https://registry.npmjs.org/@typescript-eslint%2fscope-manager: Socket timeout npm ERR! network This issue is likely due to a pr ...

While working with useEffect in Next.js, encountering the error 'ReferenceError: document is not defined' is a common issue

I need assistance with getting Bootstrap tooltips to work in my NextJS project. While I have successfully incorporated other Bootstrap components that require JS, implementing tooltips has proven challenging due to the use of document.querySelectorAll in t ...

Trigger a component update by clicking on it

I am currently working on a feature that involves displaying a new string on the page whenever a button is clicked. I have set up a service that returns the desired string when the button is tapped, and this part is functioning correctly as I can log and a ...

What is the reason for DialogContent displaying a scroll bar instead of expanding further when nested Grids with spacing are included?

My current project involves working on a form displayed in a dialog window. To adjust the layout of the form's fields, I utilize multiple Grid elements nested within another Grid. However, I've encountered an issue where adding any spacing to the ...

Tips on incorporating a callback function within the setState function

I've encountered a problem with my click handler. Initially, it was working fine like this: handleClick = () => { const { isCalendarOpen } = this.state; this.setState ({ isCalendarOpen: !isCalendarOpen }); ...

Exporting Data and Utilizing a Steady Data Table

I have incorporated the Fixed Data Grid into my latest project. https://facebook.github.io/fixed-data-table/example-sort.html My goal is to generate csv and pdf reports from the data displayed on the grid. Could you please advise me on how to export gri ...

Creating a dynamic dropdown menu where the available options in one select box change based on the selection made in another

Looking at the Material-UI Stepper code, I have a requirement to create a select element with dynamic options based on the selected value in another select within the same React component. To achieve this, I wrote a switch function: function getGradeConte ...

Attempting to iterate over the array of objects in order to discover a match

I am currently working with an object structure that resembles the one shown in the image linked below. My goal is to compare the inner object properties (such as massing type id) with existing IDs. If there is a match, I want to retrieve the name of that ...

What is the best way to send FormData from a React JS axios post request to a Node server?

I am facing an issue where the form data is not reaching the node server even though it shows in the network payload at the time of request. Below are the snippets from different files involved in the process. let formData = new FormData(); // fo ...

How can I fix the ReferenceError that says ToolBar is not defined?

My journey with a new Next.js project began around three days ago. After updating everything, I proceeded to include the following dependencies: yarn add @material-ui/core yarn add @mui/icons-material yarn add @mui/material This is the code snippet that r ...

What is the process of integrating TextField modifications into state using MaterialUI and Redux?

When using React / Redux and MaterialUI, I have set up a component that needs to either check the user's location or retrieve the latitude/longitude based on the address input. Upon clicking a button, I want the address entered in a TextField to be v ...