WebSockets Issue in React and Node.js [closed]

I'm setting up real-time updates in my React application using WebSockets with a Node.js server, but the client isn't receiving messages. Here's my server-side code:

javascript

Collapse

Wrap

Copy
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
    ws.send('Hello from server!');
});
And my React client-side code:

javascript

Collapse

Wrap

Copy
import React, { useEffect } from 'react';
import { w3c } from 'ws';
function App() {
    useEffect(() => {
        const ws = new w3c('ws://localhost:8080');
        ws.onmessage = function(event) {
            console.log('Received: ' + event.data);
        };
    }, []);
    return <div>App</div>;
}
export default App;

What’s wrong with this setup, and how can I fix it to ensure the client receives messages?

The first question addresses a common full-stack challenge: implementing real-time updates using WebSockets in a React application with a Node.js backend. The scenario involves a client not receiving messages from the server, a frequent issue in WebSocket implementations. The question includes server-side and client-side code, making it concrete and actionable.

Technical Details: The server uses the ws library to set up a WebSocket server on port 8080, sending a test message upon connection. The React client uses the useEffect hook to establish the connection and listen for messages, but the issue is that no messages are received. This reflects a typical debugging scenario for full-stack developers integrating front-end and back-end real-time features.
Relevance: WebSockets are crucial for applications requiring instant updates, such as chat apps or live dashboards. The question is likely to attract answers discussing connection setup, error handling, and potential library mismatches, aligning with Stack Overflow’s focus on specific technical problems.
Validation: Searches for “React WebSockets” on Stack Overflow revealed numerous similar questions, such as Proper way of using React hooks + WebSockets, confirming this is a common issue.

Is there a way to tree-shake decorator in webpack build?

Repro demo link: https://github.com/xcatliu/webpack-decorator-tree-shake

Input:

// src/index.ts

import { add } from './math';

(window as any).add = add;
// src/math.ts

export function add(a, b) {
  return a + b;
}

function sealed(constructor) {
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}

/*#__PURE__*/
@sealed
class Foo {
  sub() {
    console.log("hello");
  }
}

In this case, class Foo is not imported or used in index.ts

However, the built result dist/bundle.js has the code console.log("hello")

Is there a way to tree-shake decorator in webpack build?

Related issue:

Vite seems to have a plugin to do this but webpack haven’t.

How to catch 401 or other errors in Tableau embed ReactJs

I have a React web app in which I am embedding Tableau reports. I am also using JWT token for security. When a user is not authorize to view a report I want to show an error message on the page however there is no way I am able to find to listen to the error.

import React, { useEffect, useRef } from "react";

const TableauViz = ({ src, options, token }) => {
   const vizContainer = useRef(null);

   useEffect(() => {
      // Initialize the Tableau Viz web component
      const vizElement = document.createElement("tableau-viz");
      vizElement.id = "tableauViz";
      vizElement.src = src;
      vizElement.token = token;

      // Add options as attributes
      for (const [key, value] of Object.entries(options)) {
         vizElement.setAttribute(key, value);
      }

      // Append the viz element to the container
      vizContainer.current.innerHTML = "";
      vizContainer.current.appendChild(vizElement);
   }, [src, options]);

   return <div ref={vizContainer} className="tableau-viz-container m-auto" />;
};

export default TableauViz;

Above is my code. Users are able to view the reports if they are authorized. Also this code internally fires a network request for checking the authorization but that is not in my control so when it throws 401 or some other error then I am unable to catch and display it.

As per the docs, I did try listening to the onVizLoadError event but that didn’t work.
Tableau documentation for listening to error

   function handleError(ev){
      console.log("handleError", ev);
   }

   useEffect(() => {
      // Initialize the Tableau Viz web component
      const vizElement = document.createElement("tableau-viz");
      vizElement.id = "tableauViz";
      vizElement.src = src;
      vizElement.token = token;
      vizElement.onVizLoadError = handleError;

      // Add options as attributes
      for (const [key, value] of Object.entries(options)) {
         vizElement.setAttribute(key, value);
      }

      // Append the viz element to the container
      vizContainer.current.innerHTML = "";
      vizContainer.current.appendChild(vizElement);
   }, [src, options]);

I tried listening to onVizLoader like this, even tried to it view addeventlistener but they did not work, nothing printed in the console.

Any help will be appreciated.

Expo SDK 52 Flickering of StatusBar when navigating to another screen on Android

I’m experiencing issues using Expo-managed code on Android (SDK 52). I have followed the documentation on the Expo site, however, when I navigate to another screen, I notice the Statusbar flickers (to the previous color) if the target screen has a different statusBarBackgroundColor.

// _layout.tsx

      <>
        <Stack>
          <Stack.Screen
            name="index"
            options={{
              headerShown: false,
              statusBarBackgroundColor: 'yellow',
              navigationBarColor: 'yellow'
            }}
          />

          <Stack.Screen
            name="testPage"
            options={{
              presentation: 'fullScreenModal',
              animation: 'slide_from_left',
              headerShown: false,
              statusBarBackgroundColor: 'red',
              navigationBarColor: 'red'
            }}
          />
        </Stack>
      </>


// target screen is testPage

  return (

    <SafeAreaView style={[styles.container, { flex: 1, backgroundColor : 'red' }]}>
      <StatusBar style="light" animated={true} backgroundColor='red' translucent={true}/>
      <TouchableOpacity onPress={()=> router.back()}>
          <Text>Test</Text>
      </TouchableOpacity>
    </SafeAreaView>
 
  )

Following the expo documentation, I needed to add the StatusBar component at a screen level otherwise, I had a 1-second delay with the statusbar color being updated. This fixed the delay issue, but the downside is, this is now causing flickering/flashing on the statusbar.
I’m testing this on a Samsung Galaxy S22. Any help would be much appreciated.

Lit – Light DOM Memory Leaks

A few years ago I decided to migrate an old vanilla JS frontend to Lit as I could port the project in stages while keeping rest of code the same. Lit was mostly used for the reactivity component which greatly simplifies a code base.

Lit was mostly used with light DOM as the intention was never to create modular components but rather use the functionality to build a reactive front end.

   createRenderRoot() {
        return this;
    }

I’m busy converting this same app to a SPA (single page application). I’ve noticed that I’m having memory leaks where loading the same page over and over again (for test purposes) causes the memory footprint to constantly increase with an increase in objects/arrays and other items which I’m not too sure of what they mean.

Coming to my question, what is the best way to make sure there are no memory leaks with with multiple nested Lit components where there might be references between them ?

I’m currently doing the following without much success as setting properties in disconnectCallback can cause other issues like the updating cycle triggering again. I’m also manually storing things like intervals and custom events where they are not part of Lit html events and destroying them in disconnectCallback .

static properties = {
        mainClass: { type: Object },
        models: { type: Array },
        selectedModel: { type: Object },
        activeTab: { type: String },
        selectedFileDataSource: { type: Object },
        selectedFilePrediction: { type: Object },
        eventsCreated: { type: Boolean },
        selectedFilterCollection: { type: Object },
        open: { type: Boolean },
    };

    constructor() {
        super();
        this.mainClass = {};
        this.models = [];
        this.selectedModel = {};
        this.activeTab = 'model';
        this.selectedFileDataSource = null;
        this.selectedFilePrediction = null;
        this.eventsCreated = false;
        this.selectedFilterCollection = null;
        this.open = false;
    }

    createRenderRoot() {
        return this;
    }

    disconnectedCallback() {

        this.mainClass = null;
        super.disconnectedCallback();
    }

Getting OSM map object from iframe

Is it possible with maplibregl to load a map (created with umap or a similar service) from source and add layers or markers to it?

var mapframe = document.createElement("iframe");
mapframe.src = "//umap.openstreetmap.de/en/map/untitled-map_87034?scaleControl=false&miniMap=true&scrollWheelZoom=true&zoomControl=true&editMode=disabled&moreControl=true&searchControl=null&tilelayersControl=null&embedControl=null&datalayersControl=true&onLoadPanel=none&captionBar=false&captionMenus=true#15/50.7806/6.1281";
        el.parentNode.appendChild(mapframe);

const marker = new maplibregl.Marker()
            .setLngLat([12.550343, 55.665957])
            .addTo(mapframe);

Of course that does not work. I figured that I have to get the map object somehow, but don’t know how and if that is possible.

Cybersource Refund Issue getting Not Authorized /401

I am integrating CyberSource payment gateway using JavaScript. The payment part is working and going through, However i am stuck at refunds. Always getting not authorized error.
The API keys are correct. Checked Multiple times.

Note: –
I am using CyberSource’s Secure Acceptance Hosted Checkout for Payment and for Refund, REST API endpoint, Location – Middle East Region.

From successful Payment Response i have saved the follwoing transaction reference to my DB to initiate a refund – auth_trans_ref_no & auth_reconciliation_reference_number. In the below given code i am using auth_trans_ref_no. Tried both though

This is how i process a refund Request

after Extracting Booking details from DB under ticket

const refundEndpoint = `https://api.cybersource.com/pts/v2/payments/${ticket.cybersourceConfirmationId}/refunds`;

const refundPayload = {
  clientReferenceInformation: {
    code: ticket.transactionId,
  },
  orderInformation: {
    amountDetails: {
      totalAmount: Number(refundAmount).toFixed(2),
      currency: "QAR",
    },
  },
};

const payloadString = JSON.stringify(refundPayload);

const digest =
  "SHA-256=" +
  crypto
    .createHash("sha256")
    .update(payloadString)
    .digest("base64");

const vCDate = new Date().toUTCString();

const host = "api.cybersource.com";
const requestTarget = `post /pts/v2/payments/${ticket.cybersourceConfirmationId}/refunds`;

const vCMerchantId = process.env.CYBERSOURCE_MERCHANT_ID;
const keyId = process.env.CYBERSOURCE_SHARED_API_KEY_ID;
const secretKey = process.env.CYBERSOURCE_SHARED_API_SECRET;

const signingString =
  `host: ${host}n` +
  `date: ${vCDate}n` +
  `(request-target): ${requestTarget}n` +
  `digest: ${digest}n` +
  `v-c-merchant-id: ${vCMerchantId}`;

const computedSignature = crypto
  .createHmac("sha256", secretKey)
  .update(signingString)
  .digest("base64");

const signatureHeader = `keyid="${keyId}", algorithm="HmacSHA256", headers="host date (request-target) digest v-c-merchant-id", signature="${computedSignature}"`;

const headers = {
  host,
  signature: signatureHeader,
  digest,
  "v-c-merchant-id": vCMerchantId,
  date: vCDate,
  "Content-Type": "application/json",
};

try {
  const response = await axios.post(refundEndpoint, refundPayload, { headers });
    //If true
  } else {
    //If False
} catch (error) {
  //If Error
}

This is the Link to CyberSource Docs

Processor – Asia/Middle East and Africa Gateway
API- Rest API

I have been stuck on this for about 5 days now. Tried multiple formats and everything. but nothing seems to work. All help is appreciated. If you need anything else please do tell

Using .getOwnPropertyNames() method to find specific property [duplicate]

So i have a “template” function which is initialized like this:

let createMenuOption = function(containerName, providedText, actionApplied)

containerName function argument is always passed in as a reference to an object element, here’s an example of how this function is called in my code:

stopMusic: createMenuOption(menuOptions.stopMusic, "Quiet", musicQuiet)

Previously, having a lot of nameless/unidentifiable divs which this function creates worked for me, but as project grew, I found myself in need of actually further manipulating some of the created divs.

So currently, I’m trying to assign them an ID based on the containerName so that I’ll be able to reference the needed div blocks in other functions.
Unfortunately, I can’t quite figure out the logic of how I can extract object name and property name from the containerName argument, as when I’ve tried to treat it as a string and did something like this:
`${containerName.split(".")[1]}` – i just got an error that TypeError: containerName.split is not a function – it’s understandable that this throws an error as an object CAN’T be manipulated like a string, but I’m honestly stuck on how I can just extract the property name as string otherwise.

here’s some code/pseudocode of what I’ve already figured out for the moment:

const objectToArray = function (objectToChange, valueToExtract) {
       const turnedArray = Object.getOwnPropertyNames(objectToChange); //to extract all objects keys and put them into an array of strings
       const idOfValueToExtract = turnedArray.indexOf(valueToExtract);  //to find the index of the specific element passed into the createMenuOption as a containerName 
    }

    // containerName.setAttribute("id", `${Object.getOwnPropertyNames(object from which containerName comes)[id of containerName passed into the function]}`);

I know that this is far from the complete solution, but I’m kind of stuck with this problem now… I’d really appreciate any assistance with this – since I don’t work with jQuery yet, I’d need a pure JS solution for this problem (if one exists)

How do i test Lexical Toolbar Plugin and trigger onError of initialConfig?

I am using ToolbarPlugin from Lexical and using the code from Lexical repo. My Sonarqube has flagged below code for test coverage and am not sure what test needs to be inlcuded:

`const $updateToolbar = useCallback(() => {
    const selection = $getSelection();
    if ($isRangeSelection(selection)) { // This line requires a test
      setIsBold(selection.hasFormat('bold'));
      setIsItalic(selection.hasFormat('italic'));
    }
  }, []);`

Current tests which are included are to format text to Bold, Italic individually and then format text string Bold and Italic together. In addition i have added a test to check when empty string is passed nothing is actually formatted and then string isn’t present in editor

Similarly below the below line of code from same plugin needs attention:

`editor.registerCommand(
        SELECTION_CHANGE_COMMAND,
        (_payload, _newEditor) => {
          $updateToolbar();// this line and the below line requires test(s)
          return false;`// 

2nd Part of question is about triggering onError event present in Initialconfig of Lexical. This is the config:

`const initialConfig = {
  namespace: 'RichtextEditor',
  onError(error: Error) {
    >>throw error;
  },`// This line is flagged to add test

i have a prop for the editor which when set is styling the editor with error message, but to trigger this onError is ask from SonarQube.
Am using React Testing library to write tests, i need help to understand whats missing in the tests? Thanks in advance.

Scroll issue with DND kit sortable and react virtual

I encountered a scrolling issue when using react-virtual for virtual scrolling in combination with dnd-kit for drag-and-drop. When dragging an item inside the virtualized list, the scroll behavior becomes inconsistent, causing unexpected jumps or freezes.

Steps to Reproduce

Implement a virtualized list using react-virtual.

Enable drag-and-drop functionality using dnd-kit.

Drag an item while attempting to scroll.

Notice the scrolling issue (e.g., unexpected jumps, no scrolling, or laggy behavior).

Expected Behavior

The list should scroll smoothly while dragging items.

The drag-and-drop functionality should work without interfering with scrolling.

Actual Behavior

Scrolling stops working or behaves unpredictably when an item is being dragged.

POC Link
https://codesandbox.io/p/sandbox/8n2q3f

Additional Context
I suspect this issue occurs due to how both libraries handle event listeners and scroll management. Any guidance or possible workarounds would be appreciated.

Angular Material: Prevent blur event when mat-option is selected in autocomplete

I’m trying to achieve a scenario where user has 2 different cases like below:

  1. User can select an option from the autocomplete option list

OR

  1. User can type a value if it matches then its considered correct and the value is shown on blur and few other operation happens.

In my case scenario 2 is working perfectly. Issue is occurring with the 1st. Whenever I select an option then the blur event also gets triggered.

I’ve researched and found an answer in the GitHub that this can be resolved using the answer from this link. However, this is now outdated in the modern angular versions from v16 where relatedTarget returns NULL whenever the action happens from a material component (Refer this answer).

How can I achieve this scenario to not trigger blur when user selects a mat-option?

I’ve created a sample example where on select of an option both 1 & 2 are getting consoled from their respective event.

Expected scenario: Only 2 should get consoled on option select.

Node / express / ejs / Uncaught SyntaxError: missing ] after element list

I’m running a express server and render a list.
This is the code of the route:

try {
    let result = await servCollections.prepareDataForListCollections();
    let colls = result.data;
    let messages = result.messages;
    res.render('../views/pages/listcollections', { daten: colls, mess: messages });
} catch (err) {
    console.error(`Error while getting collections `, err.message);
    next(err);
}

In my ejs view I want to pass the mess variable to a javascript function like so:

<main>  

<script>populateMultiMessages( <%= mess %> )</script> 

Then I got the above error, which I can`t understand. Here is the content from mess in a debugger view:
debug window of array messages

Calling API displays the whole JSON as a text in the DOM [closed]

FIX: you dont have to require the API… the JS does its work whenever the DOM is loaded… thanks deceze:

<?php require 'includes/api/load_images.php';?>

I have a simple API that calls images from my database via JSON. Everything works fine, but there is text containing the JSON (which i dont want).
The problem is the text at the top

Here is my html where i call all the necesearry files:

<script src="/../public/js/gallery.js" defer></script>
<script src="/../public/js/lightbox.js" defer></script>
<?php require 'includes/api/load_images.php';?>
<div class="gallery-grid">
    <div id="gallery">
        <!-- Betöltött képek jelennek meg itt -->
    </div>
</div>
<button id="loadMore" class="gallery-loadMore">Továbbiak betöltése</button>

<?php require 'includes/website_essentials/lightbox.php';?>

Here is my php API:

<?php
require_once __DIR__ . '/../../database/db_connect.php'; // Adatbázis kapcsolat
require_once __DIR__ . '/../../includes/errorhandler.php'; // Hibakezelő

$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 6;
$offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;

$sql = "SELECT * FROM gallery ORDER BY uploaded_at DESC LIMIT $limit OFFSET $offset";
$result = $conn->query($sql);

$images = [];
while ($row = $result->fetch_assoc()) {
    $images[] = $row;
}

echo json_encode($images);
$conn->close();
?>

And here is my JS:

document.addEventListener("DOMContentLoaded", function () {
    let offset = 0;
    const limit = 6;

    function loadImages() {
        fetch(`/includes/api/load_images.php?limit=${limit}&offset=${offset}`)
            .then(response => response.json())
            .then(images => {
                console.log(images);
                if (images.length === 0) {
                    document.getElementById("loadMore").style.display = "none";
                    return;
                }

                images.forEach((image, index) => {
                    const galleryItem = document.createElement("div");
                    galleryItem.classList.add("gallery-item");

                    const imgElement = document.createElement("img");
                    imgElement.setAttribute("loading", "lazy");
                    imgElement.setAttribute("data-index", index);
                    imgElement.classList.add("gallery-img");
                    imgElement.src = `/${image.gallery_image}`;
                    imgElement.alt = image.title; 
                    imgElement.title = image.title;
                    galleryItem.appendChild(imgElement);
                    document.getElementById("gallery").appendChild(galleryItem);
                });

                // Képek betöltése után esemény kiváltása (ez a lightbox.js fájlban van kezelve)
                document.dispatchEvent(new Event("imagesLoaded"));

                offset += limit;
            })
            .catch(error => console.error("Hiba:", error));
    }

    loadImages();

    document.getElementById("loadMore").addEventListener("click", loadImages);
});

Can’t able to access element from Object in ReactJs

I have 4 lines to code

console.log(Object.keys(data));
console.log(data);
console.log(data['createTs']);
console.log(data.createTs);

output for 1st line :

[
    "supplierName",
    "supplierNbr",
    "itemNbr",
    "category",
    "subCategory",
    "receivingNodesInbound",
    "whseOrderIds",
    "orderType",
    "overviewStatus",
    "fromNode",
    "orderSubTypes",
    "itemDesc",
    "importOrDomestic",
    "event",
    "systemCreatorId",
    "createBy",
    "channelMethod",
    "source",
    "freight",
    "singleCreateTs"
]

Output for 2nd line:

{
    "supplierName": "",
    "supplierNbr": "",
    "itemNbr": "",
    "category": [],
    "subCategory": [],
    "receivingNodesInbound": "",
    "orderType": [
        "PO"
    ],
    "overviewStatus": [],
    "orderSubTypes": [],
    "systemCreatorId": [],
    "createBy": "",
    "channelMethod": [],
    "source": [],
    "orderIds": [],
    "hostNbr": [],
    "lineStatuses": [],
    "orderSubTypeList": [],
    "categories": [],
    "createTs": {
        "startDate": "NaN-NaN-NaN"
    }
}

3rd and 4th line is giving “undefined”.
I couldn’t understand why its giving undefined. How can I access createTs from data object?

navigator.serviceWorker.ready never resolves on Chrome only. Edge & Opera work, Firefox errors

In the following code, the ServiceWorker.READY method/promise never resolves: –

    if ("serviceWorker" in navigator) {                 
        await navigator.serviceWorker.register('/Vanilla/CacheManager.js', { scope: '/Vanilla/', type: 'module' })
            .then(reg => {
                    console.log('SW Registered');
                })
            .catch(err => {
                console.log('SW Registration failed with ' + err)
            });
            
        await navigator.serviceWorker.ready
            .then(subscription => {cacheManagerSubscription = subscription})
                    .catch(err => {
                            console.log('Cache Manager Subscription failed with ' + err)
                        });
    }

I have read many answers here and elsewhere about changing the scope for the Service-Worker but the above seems to work with Edge and Opera, just not Chrome (Some JS exception is occuring on FF)

This is the SW code: –

import {config} from "/Vanilla/config.js"

const CACHE_NAME    = config.cacheName
console.log(CACHE_NAME)
    
self.addEventListener('install', (e) => 
{
    try {
    e.waitUntil(
        caches.open(CACHE_NAME).then((cache) => {
            return cache.addAll([
                '/Vanilla/test_sg9.html',
                '/Vanilla/Scales.png',
                '/Vanilla/GlobalStateManager.js',
                '/Vanilla/HomePage.js',
                '/Vanilla/RowDetails.js',
                '/Vanilla/ScrollGrid.css',
                '/Vanilla/ScrollGrid.js',
                '/Vanilla/CacheManager.js',
                '/Vanilla/Utils.js',
                '/Vanilla/test_sg.json',
                '/Vanilla/WebPage.js',
                '/Vanilla/coa.css',
                '/Vanilla/coa.svg',
                '/Vanilla/caller.css'
          ]).then(async () => await self.skipWaiting())
        })
    )
    } catch(err) {
        console.log(err);
    }
    console.log("Leaving install")
})
    
self.addEventListener('activate', (e) => 
{
    e.waitUntil(
        caches.keys().then((keyList) => {
            return Promise.all(keyList.map((key) => {
                if (key !== CACHE_NAME) {
                    console.log('Removing cache', key);
                    return caches.delete(key);
                }
            }))
        })
    )

    e.waitUntil(self.clients.claim())
})

self.addEventListener('fetch', (e) => 
{
    console.log(e.request.url + " my origin " + self.location.origin)
    if (e.request.url.startsWith(self.location.origin)) {
        e.respondWith(
            caches.match(e.request.url, { ignoreVary: true }).then((response) => {
                console.log("Request " + e.request.url)
                if (response) {
                    console.log("Response " + response.url)
                } else
                    console.log("No MATCH")

                return response || fetch(e.request)
            })
        )
    } else
        return fetch(e.request);
})

I thought that maybe it just an old cache on Chrome but I’ve changed the cache version and always delete browser history and unregistered running service workers but just can’t get any feedback from Chrome 🙁

I did see this work around in SO. Is that the best I can hope for?

Full code can be found here.

Working/failing demo can be found here.

Manifest: –

{
  "short_name": "Vanilla",
  "name": "Vanilla Web App",
  "description": "ScrollGrid Vanilla Javascript demo",
  "icons": [
    {
      "src": "/Vanilla/Scales.png",
      "sizes": "128x128",
      "type": "image/png",
      "purpose": "any"
    },
    {
      "src": "/Vanilla/Scales.png",
      "sizes": "128x128",
      "type": "image/png",
      "purpose": "maskable"
    }
  ],
  "start_url": "/Vanilla/test_sg9.html",
  "background_color": "#00ccdd",
  "theme_color": "#00ccdd",
  "display": "fullscreen"
}