WebSocket Disconnection on iOS Devices with React and Stomp Integration

I am currently grappling with disconnection issues while implementing WebSocket communication with Stomp in a React application on iOS devices.

The Stomp server, integral to the architecture, is hosted on a Spring Boot application.

The communication between the React application and the Stomp server is facilitated by the esteemed react-stomp-hooks library.

Currently I have encounter 2 issues.

Issue 1: Disconnection Post-Device Unlock

Upon entering the React application via the browser(safari), seamless functionality ensues. However, when the device undergoes the transition from a locked to an unlocked state, The attempts to communicate with the Stomp server yield an absence of transmitted messages. This is fix by refreshing the page.

Issue 2: Absence of Communication on Homepage Integration

While saving the web application as shortcut on iOS device’s homepage, No connection has been implemented to the Stomp server.

Stomp Server URL:
https://stomp.domain.com

The library I am using to interact with the stomp server: react-stomp-hooks

Sample of my code thats shows how I am integrating with the Stomp server:


export default function App() {
    useScrollToTop();

    return (
        <ThemeProvider>
            <StompSessionProvider url={STOMP_SERVER}>
                <Router/>
            </StompSessionProvider>
        </ThemeProvider>
    );
}

const stompClient = useStompClient();
    useSubscription(generateStompSubscriptionUrl(scaleId), (message) => {
        handleTerminalChange(message.body)
    });
    const sendMessage = (message) => {
        if (stompClient) {
            stompClient.publish({
                destination: generateStompSendDestinationUrl(scaleId),
                body: message,
            });
        } else {
            //Handle error
        }
    };

  1. Are there specific configurations or settings that demand adjustment to circumvent these disconnection challenges on iOS devices?
  2. Is there available insight into whether Apple may be implementing restrictions on WebSocket connections within web applications for specific reasons?

Load any website inside my react js app for preview

I am making a app where users can preview their website inside my app in a small preview window.

first I thought for going with iframe but there are several issues with iframe as many website uses ‘X-Frame-Options’ to ‘deny’ which blocks the site from loading in iframe.

I need a proper way to load the site inside the preview window if possible.

If not is there a way to know which site will load and which will not.

Para que sirve un proyecto educativo [closed]

Un proyecto es un conjunto de procedimientos y ctividades que suceden entre si para el cumplimiento de un objetivo en especifico. Como su nombre lo indica en una proyección que incluya la solucion de un problema o la proposicion de una nueva idea y sus posibles resultados.

React-leaflet doesn’t clear routes when adding additional waypoints

I’m trying to clear the route when I add a new waypoint. Only two waypoints should should show. However, when adding an additional waypoint, Leaflet will show the old route instead of clearing it. I checked the console logs and it definitely only shows two waypoints, and the first one is “spliced” out and replace with a new waypoint. Any ideas on how to reset the map?

import { useEffect, useRef } from 'react';
import Leaflet from 'leaflet';
import * as ReactLeaflet from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import "leaflet-routing-machine"
import { useMapStore } from '@/store/mapStore'

const { MapContainer, FeatureGroup, GeoJSON, useMap } = ReactLeaflet;

function MyComponent() {
  const map = useMap()
  const lat = useMapStore(state => state.lat)
  const lng = useMapStore(state => state.lng)

  // https://www.npmjs.com/package/leaflet-routing-machine/v/0.2.0

  useEffect(() => {
    Leaflet.Icon.Default.mergeOptions({
      iconRetinaUrl: 'images/marker-icon-2x.png',
      iconUrl: 'images/marker-icon.png',
      shadowUrl: 'images/marker-shadow.png'
    });

    let routeControl = Leaflet.Routing.control({
      waypoints: [
        Leaflet.latLng(-35.3080, 149.1250),
        Leaflet.latLng(-35.3080, 149.1250)
      ],
      router: Leaflet.Routing.mapbox(process.env.NEXT_PUBLIC_MAPBOX_KEY)
      // your other options go here
    }).addTo(map);

    if (lat) {
      routeControl.spliceWaypoints(0, 1, Leaflet.latLng(-35.3080, 149.1250))

      const latlng = Leaflet.latLng(lat, lng)

      routeControl.spliceWaypoints(0, 1, latlng)
      routeControl.route()
    }

    routeControl.getWaypoints().forEach((waypoint, index) => {
      console.log(waypoint)
    })

  }, [map, lat, lng])
  return null
}

const Map = ({ children, className, width, height, ...rest }) => {
  return (
    <MapContainer
      {...rest}>
      <MyComponent />
      {children(ReactLeaflet, Leaflet)}
    </MapContainer>
  )
}

export default Map;

Screenshots below:
Adding the first route

Adding a new second waypoint leaves the old route in the map

Checked the API docs here: https://www.liedman.net/leaflet-routing-machine/api/

Problems understanding the import … from … syntax

For my project Iam trying to use an javascript picture viewer:
https://fengyuanchen.github.io/viewerjs/

In the github readme https://github.com/fengyuanchen/viewerjs/blob/main/README.md
it says the viewer module can be imported by the following syntax:

import Viewer from 'viewerjs';

From my little javascript knowledge, I always thought that the from refers to file, so syntax would be something like this path information and proper file ending:

import Viewer from './viewer.js';

I also took a look at the scource code and all submodules are referenced without file endings:

import DEFAULTS from './defaults';
import TEMPLATE from './template';
import render from './render';
import events from './events';
import handlers from './handlers';
import methods from './methods';
import others from './others';

Can somebody please explain why in the mentioned cases, something like this is okay?

import Viewer from 'viewerjs';

How to read the selected dropdown list from HTML to javascript

                        <div class="form-group">
                            <label for="repId">REP ID</label> 
                            <select name="item" class="form-control " style="font-weight: bold;" ng-model="idDropdown">                                     
                                <option value="{{item}}">Select REP ID</option>
                                <option ng-repeat="item in columnData" value="{{item}}">{{item}}</option>
                            </select>
                        </div>

I have tried to get the value selected from dropdown list to Javascript. But I am getting undefined. Below is the code which I have tried in Javascript to read the item value.

var repId= $(‘#item’).val();

I can not show an image using react

I’m triying to show an image using react, but i don’t know why it did not works.

First, I created this component:
This is the component:

import React from "react";


function Tarjeta (){
    return(
      <div className="tarjeta-jugador">
        <h1 className="nombre-jugador">Alvaro Montero</h1>
        <img className={require('../imagenes/montero.jpg')} alt='Foto Montero' />
      </div>
    )
}
export default Tarjeta;

And This is how I’m triying to render it,

import './App.css';
import Tarjeta from './componentes/Tarjeta'

function App() {
  return (
    <div className="App">
      <Tarjeta />
    </div>
  );
}

export default App;

This is how it looks

I want to know why is not working and how may i show it, usgin this sintaxis. My path is correct.

Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading ‘Upload’) – tus-js-client

Hello Stack Overflow Community,

I am working on a Next.js application where I need to upload videos to Vimeo. I’m using tus-js-client for the upload functionality. However, I’m encountering an error when trying to initialize a new tus upload.

The error message is:

Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'Upload') - tus-js-client

code

import React, { useState } from 'react';
import { Button } from '@mui/material';
import tus from 'tus-js-client';

const VimeoUploadComponent = () => {
  const [videoFile, setVideoFile] = useState(null);

  // This function will be triggered when the user clicks the upload button
  const handleUpload = async () => {
    console.log("clicked")
    if (!videoFile) {
      alert('Please select a file first.');
      return;
    }

    const accessToken = process.env.NEXT_PUBLIC_VIDEO_KEY;

    
    // Initialize a new tus upload
    var upload = new tus.Upload(videoFile, {
      endpoint: "https://api.vimeo.com/me/videos",
      retryDelays: [0, 1000, 3000, 5000],
      metadata: {
        filename: videoFile?.name,
        filetype: videoFile?.type
      },
      headers: {
        Authorization: `bearer ${accessToken}`,
        Accept: "application/vnd.vimeo.*+json;version=3.4",
      },
      uploadSize: videoFile?.size,
      onError: function(error) {
        console.error("Failed because: " + error)
      },
      onProgress: function(bytesUploaded, bytesTotal) {
        var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2)
        console.log(bytesUploaded, bytesTotal, percentage + "%")
      },
      onSuccess: function() {
        console.log("Download %s from %s", upload.file.name, upload.url)
      }
    });

    console.log("uploaded file", accessToken)

    // upload.start();
  };

  const handleFileChange = (event) => {
    console.log("handling file")
    const file = event.target.files[0];
    if (file) {
        console.log("selected file", file)
      setVideoFile(file);
    }else{
        console.log("not selected")
    }
  };

  return (
    <div>
 <input
        accept="video/*"
        style={{ display: 'none' }}
        id="raised-button-file"
        type="file"
        onChange={handleFileChange}
      />
      <label htmlFor="raised-button-file">
        <Button variant="raised" component="span">
          Choose File
        </Button>
      </label>
      <Button
        variant="contained"
        onClick={handleUpload}
      >
        Upload to Vimeo
      </Button> 
    </div>
  );
};

export default VimeoUploadComponent;

The issue occurs at the line where I try to create a new instance of tus.Upload. I’ve already ensured that tus-js-client is installed in my project. I’m not sure if I’m importing or using the Upload class incorrectly, or if it’s an issue with how tus-js-client interacts with Next.js.

Has anyone encountered a similar issue or can offer any insights on how to resolve this? Any help or suggestions would be greatly appreciated!

Thank you!

Return statement not printing to console?

When I run the following code, it only prints to the console “Checkpoint X” but not the return statement:

function match(player, computer){
    
    console.log(`Player choice is ${player} and computer choice is ${computer}`);

    if (player === computer){
        console.log("Checkpoint 1")
       return "It's a draw!";
    } else if (player == 'Rock' && computer == 'Paper'){
        console.log("Checkpoint 2")
        return "Computer wins";
    } else if (player == 'Rock' && computer == 'Scissors'){
        console.log("Checkpoint 3")
        return "Player wins";
    } else if (player == 'Paper' && computer == 'Rock'){
        console.log("Checkpoint 4")
        return "Player wins";
    } else if (player == 'Paper' && computer == 'Scissors'){
        console.log("Checkpoint 5")
        return "Computer wins";
    } else if (player == 'Scissors' && computer == 'Rock'){
        console.log("Checkpoint 6")
        return "Computer wins";
    } else if (player == 'Scissors' && computer == 'Paper'){
        console.log("Checkpoint 7")
        return "Player wins";
    } else {
        return "Match error!";
    }
}

However, when I enter in the console directly match(player,computer); it prints to the console both “Checkpoint X” and the associated return statement.

Does anyone know why this is?

How do I implement the `fromObject` method for customize class in FabricJS (with typescript)

I am trying to make a customize class for a custom object. The object needs to be load with JSON, so I would have to implement fromObject method.

I use Typescript and FabricJS v5.3.0.

When i load my json with canvas.loadFromJSON(...) i have this error :

Uncaught TypeError: Cannot read properties of undefined (reading ‘fromObject’)

My custom class :

import { fabric } from 'fabric';
import { IRectOptions } from 'fabric/fabric-impl';

export class CustomRect extends fabric.Rect {

    constructor(options: ICustomRectOptions) {
        super(options);
    }

    toObject(propertiesToInclude?: string[]) {
        propertiesToInclude = (propertiesToInclude || []).concat(
            ['echo']
        );
        return super.toObject(propertiesToInclude);
    }

    static fromObject(object: any): CustomRect {
        return new CustomRect(object);
    }

    _render(ctx: CanvasRenderingContext2D) {
        super._render(ctx);
    }
}

I tried with a normal and static method, but always the same error message.

JS/Jquery change class

is it possible if the label element contains ‘false’ to change the class of the parent div. (and only from the one)?

<div class="myclass">
  <input type="checkbox" name="water-list" value="school-1" case="registered" id="school-1" class="CheckBox">
  <label for="true">bla</label>
</div>
<div class="myclass">
  <input type="checkbox" name="water-list" value="school-2" case="registered" id="school-2" class="CheckBox">
  <label for="true">bla</label>
</div>
<div class="myclass">
  <input type="checkbox" name="water-list" value="school-3" case="registered" id="school-3" class="CheckBox">
  <label for="false">bla</label>
</div>
<div class="myclass">
  <input type="checkbox" name="water-list" value="school-4" case="registered" id="school-4" class="CheckBox">
  <label for="true">bla</label>
</div>

Draw arrow between two divs, regardless of their position

I want to build on this question which explains how to draw an arrow between two divs using svg, but I want to not have to position the arrow manually between the divs. Regardless of where the divs are on the page I want to be able to get the right side point of div1, the left side point of div2, and draw an arrow between them. For example, this is the code that I’ve worked out so far:

<!DOCTYPE html>
<html>
<body>

<div id="div1"><p>First div<p><div>
<div id="div2"><p>Second div<p><div>

// this was the answer from the linked question for a fixed-position arrow
<svg width="300" height="100">

        <defs>
            <marker id="arrow" markerWidth="13" markerHeight="13" refx="2" refy="6" orient="auto">
                <path d="M2,2 L2,11 L10,6 L2,2" style="fill:black;" />
            </marker>
        </defs>
    
        <path d="M30,150 L100,50" id="arr1"
              style="stroke:black; stroke-width: 1.25px; fill: none;
                     marker-end: url(#arrow);"
        />
    
</svg>

// this is my attempt to get the two coordinates I want
// and to set the path of the arrow
<script>
        var leftobj = document.getElementById("div1");
        var rightobj = document.getElementById("div2");
        var leftcoords = leftobj.getBoundingClientRect();
        var rightcords = rightobj.getBoundingClientRect();
        var startx = leftcoords.right;
        var endx = rightcoords.left;
        var starty = (leftcoords.top + leftcoords.bottom)/2;
        var endy = (rightcoords.top + rightcoords.bottom)/2;
        var linepath = `M${startx},${starty} L${endx},${endy}`;
        var arr = document.getElementById("arr1");
        arr.d = linepath
</script>

<body>
<html>

But this does not draw the arrow where I want it. Any help would be super appreciated!

Javascript Bookmark Button not update items instantly

I tried to create a bookmark system for my website where anyone can add posts in bookmark list and remove them too. But the problem I am having is that, when anyone add an item by clicking <span id="like-01" class="like-btn">Bookmark</span> span, it stores item in bookmark-items div and shows or count added items numbers in <div class="bookmarked-num">0</div>. But when I remove the item from bookmark lists, it actually removes from the bookmark-items and decrease the number from bookmarked-num div too. But this time its not live. I mean I can see it if I reload the page. How can I make it live ? I mean bookmark-items and bookmarked-num will update instantly when remove an item by toggling.

Here’s my approach:

<!DOCTYPE html>
<html>
<head>
    <style>
        a.panel-group_btn {color: #888;display:block;}
        a.like-btn { color: #888; font-size: 14px; }
        span.clicked { color: #00dfae; font-weight:bold; }
    </style>
</head>
<body>
<div class="bookmarked-num">0</div>
<div class="panel-group_btn">
    <a href="www.google.com" class="entry-title">This is a post</a>
    <div class='job-post-page-featured-bg ' expr:data-image='https://cdn.pixabay.com/photo/2017/01/19/23/46/church-1993645_640.jpg'></div>
    <span id="like-01" class="like-btn">Bookmark</span>
</div>
<div class="bookmark-items"></div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    function updateBookmarkedNum() {
        var bookmarkCount = $(".bookmark-items .bookmarked-item").length;
        $(".bookmarked-num").text(bookmarkCount);
    }
    $(".like-btn").click(function () {
        $(this).toggleClass('clicked');
        var btnStorage = $(this).attr("id");
        if ($(this).hasClass("clicked")) {
            var title = $(this).siblings(".entry-title").text();
            var image = $(this).siblings(".job-post-page-featured-bg").attr("expr:data-image");
            var url = $(this).siblings(".entry-title").attr("href");
            var bookmarkItem = `
                <div class="bookmarked-item" id="${btnStorage}">
                    <a href="${url}" class="bookmark-title">${title}</a>
                    <img src="${image}" alt="Bookmark Image">
                    <button class="remove-btn">Remove from bookmark</button>
                </div>`;
            $(".bookmark-items").append(bookmarkItem);
            localStorage.setItem(btnStorage, 'true');
            updateBookmarkedNum();
        } else {
            $("#" + btnStorage).removeClass('clicked');
            $("#" + btnStorage).siblings(".remove-btn").parent().remove();
            localStorage.removeItem(btnStorage);
            updateBookmarkedNum();
        }
        event.preventDefault();
    });
    $(document).on("click", ".remove-btn", function () {
        var itemId = $(this).parent().attr("id");
        $("#" + itemId).removeClass('clicked');
        $("#" + itemId).siblings(".remove-btn").parent().remove();
        localStorage.removeItem(itemId);
        $(this).parent().remove(); 
        updateBookmarkedNum();
    });
    $(".like-btn").each(function () {
        var mainlocalStorage = $(this).attr("id");
        if (localStorage.getItem(mainlocalStorage) === 'true') {
            $(this).addClass("clicked");
            var title = $(this).siblings(".entry-title").text();
            var image = $(this).siblings(".job-post-page-featured-bg").attr("expr:data-image");
            var url = $(this).siblings(".entry-title").attr("href");
            var bookmarkItem = `
                <div class="bookmarked-item" id="${mainlocalStorage}">
                    <a href="${url}" class="bookmark-title">${title}</a>
                    <img src="${image}" alt="Bookmark Image">
                    <button class="remove-btn">Remove from bookmark</button>
                </div>`;
            $(".bookmark-items").append(bookmarkItem);
        }
    });
    updateBookmarkedNum();
</script>
</body>
</html>

Bookmark not shows live / instant data when remove items by toggling items.

JS FizzBuzz not working, but it works if a variable is changed?

I tried FizzBuzz, but it doesnt works.
But again if i change j with o then it works;

With j;

    for (let n = 1; n <= 100; n++) {
        let j = "";
        if (n % 3 == 0) j += "Fizz";
        if (n % 5 == 0) j += "Buzz";
        console.log(o || n)
    }

With o;

    for (let n = 1; n <= 100; n++) {
        let o = "";
        if (n % 3 == 0) o += "Fizz";
        if (n % 5 == 0) o += "Buzz";
        console.log(o || n)
    }

Is j any special keyword or any reserved word? Please explain..