In React we are calling the api in one component now we use the same data of api in other component withut calling api again how we can do this? [closed]

“We want to avoid calling the API separately in each component. Instead, we’d like to call the API once and share the data across components. Currently, I’m trying to achieve this using localStorage, but I’m looking for a more optimized and efficient solution. Ideally, we want a centralized state management approach that ensures better performance and cleaner code.

How to open chrome forcibly instead of open webview when I click on my url in any app

My problem:
I have a service with web interface. The customers receives a link to the web page and click’s on it.
Depends on a customer platform – the link must be opened in a different way:

  • in case if the platform is an iOS or desktop – then nothing to do, the link can be opened in a default browser

  • in case if the platform is an android – the next flow will be performed:

    1. if the google chrome browser is installed – the link must be opened in the chrome broser not in an android system webview browser.
    2. if it is no the chrome browser installed – the play market with the browser must be opened

I have used Firebase Dynamic Links before. And it had working fine. But the firebase dynamic links will end of life at 25 august 2025. Now i need in alternative.

Now I trying to solve the first problem – open my link in the installed chrome browser. Im trying to solve it using a custom html page with the redirect:

...
<a href="intent://" + TARGET_URL + "#Intent;scheme=https;package=com.android.chrome;end;">open it in Chrome</a>
...

but it not lead to redirect into the chrome.

I tried to use such services as branch.io – but no ways to avoid opening my page in the system webview

How it can be solved?

Dragging thunderbird email into html text area gets link, not message contents

I am trying to drag an email from Thunderbird (or perhaps gmail) into a textarea.

If I open the message in Thunderbird, select everything (Ctrl-A) and drag the selected text it achieves what I am looking for.

But to simplify things more I want to drag the e-mail summary line (before you open it). However this just results in a link being pasted, of the form:

  imap-message://[email protected]@imap.gmail.com/folder#123456

I haven’t been able to work out how to get the content of the message from here in JavaScript

The module reloads when navigating to another page in Next.js

I encountered a problem that I have been investigating for two days but can’t find why it happens.

This is what the count function does in the count.js file. It runs on the server.

let n = 0

export async function count() {
  n = n + 1;
  return n 
}

This is the main page.js

import { count } from "./counter";

let GETNUMBER = await count()

export default async function Home() {
  return GETNUMBER 
}

In GETNUMBER I should get the number 2, because there is another page that also runs the same function as start.

As soon as I go to another page GO using redirect
which looks like this

import { count } from "./counter";
    
let GETNUMBER = await count()
    
export default async function GO() {
  return GETNUMBER
}

Here I get number 1.

It seems like the count.js page is reloaded again
And if I go back to page.js then I get 2 again
I don’t understand what’s going on here.
In React the module is only loaded once.

When i run: npm run build
the server should run onces all codes above this line:

export default async function Home() {

I hope I was understood I would appreciate help.

How can i extract Failed Selector URLs from Cypress Tests

I’m working on a self-healing project for Cypress, and I need to extract URLs that have failed selectors from my test files (.cy.js). My goal is to automatically log these URLs into a file for further analysis.

If a test fails due to a missing element, I want to log it in a way that’s easily readable,
like:


{  
   "url": "http://example.com/page",  
   "failedSelectors": ["#nonexistent-element", ".another-failed-selector"]  
}  

i developed a custom command in commands.js:

let currentUrl = 'unknown';
const fs = require('fs');
const path = require('path');

Cypress.Commands.add('trackUrlOnError', () => {
  Cypress.on('fail', (error, runnable) => {
    const timestamp = new Date().toISOString();
    const testName = runnable.fullTitle();
    const errorMessage = error.message;
    const selectorMatch = error.message.match(/Expected to find element: [`'](.*?)[`']/);
    const selector = selectorMatch ? selectorMatch[1] : "unknown";

    return cy.url().then((url) => {
      cy.task('logErrorDetails', {
        url,
        timestamp,
        testName,
        message: error.message,
        selector: selector

      });

      throw error; 
  });
});

and in e2e also :

let lastVisitedUrl = 'unknown';

beforeEach(() => {
  cy.intercept('GET', '**', (req) => {
    if (req.url.startsWith('http')) {
      lastVisitedUrl = req.url;
    }
  });
});

afterEach(function () {
  if (this.currentTest.state === 'failed') {
    const error = this.currentTest.err;
    cy.task('logErrorDetails', {
      url: lastVisitedUrl,
      timestamp: new Date().toISOString(),
      testName: this.currentTest.fullTitle(),
      message: error.message,
      selecteur: error.message.match(/Expected to find element: `([^`]+)`/)?.[1] || "unknown"
    });
  }
});

the problem is the url is not correctly extracted for example : https://google.com i got “https://www.google.com/xjs/_/js/k=xjs.hd.ar.W3bsuzNPU5A.es5.O/am=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA” idk why ..please help me fix this problem.

Is there any way I can make the ‘create version’ button disappear when clicked? [closed]

<button type=’button’
OnClick=’ let newVersionID=RelaticsAPI.CreateInstanceElement(“f02cb920-1316-f011-b6c2-001dd8d702ae”);

newVersionID=newVersionID.Element.ID;

RelaticsAPI.UpdateInstanceElement(newVersionID,”Name”,”Version”);

RelaticsAPI.CreateInstanceRelation([DocID], newVersionID, “1b78a05a-c21a-f011-b6c2-001dd8d702ae”); RelaticsAPI.Refresh([currentTableID]);’>New version

Sorting related issue using AG-Grid

I have issue ragarding sorting.

Library : AG grid


 colDefsMedalsExcluded: [],
    groupUseEntireRow: false,
    pinColumns: {
    isPinOption: true,
    columns: [
    {
    colId: 'Company_name',
    pinned: 'left',
    },
    ],
    },
    columnTypes: filters,
    paggination: { isPagging: false, pageSize: 10 },
    isfloatingFilter: true,
    pivotMode: false,
    components: {
    agColumnHeader: CustomToolTipHeader,
    loadingRenderer: loadingRenderer,
    },
    sideBar: columnAndfilterSidebarNoPivotNoColNoRow,
    statusBar: bottomStatusBar,
    suppressAggFuncInHeader: true,
    quickSearchFilter: true,
    aggFuncs: {
    'count(Dist)': distinctCounts,
    },
    headerHeight: 50,
    rowSelection: 'multiple',
    domLayout: 'normal',
    gridHeight: '72vh',
    multiSortKey: 'ctrl',
    ** alwaysMultiSort: false, **
    suppressFieldDotNotation: true,
    rowData:
    props.lstGovernanceScores &&
    props.lstGovernanceScores.map((x) => ({
    ...x,
    // market_cap: x.market_cap !== null ? numberWithCommas(Number(x.market_cap).toFixed(0)) : null,
    TrialStatus: props.trialStatus,
    allowDownload: true,
    })),

Issue is when I apply sorting one column to another column, previous column show sorting icon and i want to remove it from previous column, want to show only cureent selected column. I have disabled alwaysMultiSort: false.

How to deal with string with ” in it? [closed]

For example, a string '{"a":"1","b":"{"c": "2"}"}'with ” in it. When I do JSON.parse('{"a":"1","b":"{"c": "2"}"}'), there is an ‘Uncaught SyntaxError’.

So I thought about replacing ‘”‘ to ‘\”‘, which is '{"a":"1","b":"{\"c\": \"2\"}"}', and then it can be parsed correctly.

But when I tried to replace the string, I never succeed. I tried this str.replace(/\"/g, '\\"'), and it failed.

I don’t know where goes wrong, any help will be appreciated.

Node.js AsyncLocalStorage Official Example: Actual Execution Order Differs from Documentation

Problem Description

While learning about Node.js AsyncLocalStorage, I’ve encountered an interesting discrepancy. The official Node.js documentation provides an example with an expected output order, but when I execute the exact same code, I get a different sequence.

Here’s the official example code:

const http = require('node:http');
const { AsyncLocalStorage } = require('node:async_hooks');

const asyncLocalStorage = new AsyncLocalStorage();

function logWithId(msg) {
  const id = asyncLocalStorage.getStore();
  console.log(`${id !== undefined ? id : '-'}:`, msg);
}

let idSeq = 0;
http.createServer((req, res) => {
  asyncLocalStorage.run(idSeq++, () => {
    logWithId('start');
    // Imagine any chain of async operations here
    setImmediate(() => {
      logWithId('finish');
      res.end();
    });
  });
}).listen(8081);

http.get('http://localhost:8081');
http.get('http://localhost:8081');

According to the documentation, the expected output should be:

0: start
1: start
0: finish
1: finish

However, when I run this exact code, I consistently get:

0: start
0: finish
1: start
1: finish

Questions

  1. Why does the actual execution order differ from what’s described in the official documentation?
  2. Is this behavior related to Node.js event loop mechanics?
  3. How can I modify the code to ensure the output follows the “start start finish finish” pattern?
  4. Does this discrepancy impact how AsyncLocalStorage should be used in real applications?

What I’ve Tried

I’ve attempted the following approaches without achieving the documented output sequence:

  • Adjusting event loop timing by using setImmediate to send requests after the server starts
  • Replacing setImmediate with setTimeout
  • Varying delay times to control the timing of request submissions

Environment Information

  • Node.js version: v20.18.3/v22.12.0
  • Operating system: macos /ubuntu

I would appreciate any insights that explain this behavioral difference and help me understand the underlying mechanics.

generator-videojs-plugin on windows 10 error

I just fallowed this guide. Tried multiple times. but it gives an error.

Error appears after, I try npm install inside the newly created plugin folder.

generator-videojs-plugin

Full error log is longer than this. I removed the long install log part that didn’t show any errors.

6360 silly packumentCache corgi:https://registry.npmjs.org/videojs-languages cache-miss
6361 http fetch GET 200 https://registry.npmjs.org/videojs-languages 3287ms (cache updated)
6362 silly packumentCache corgi:https://registry.npmjs.org/videojs-languages set size:undefined disposed:false
6363 info run [email protected] install node_modules/husky node husky install
6364 info run [email protected] install node_modules/npm-merge-driver-install node src/install.js
6365 info run [email protected] install { code: 1, signal: null }
6366 info run [email protected] install { code: 0, signal: null }
6367 warn cleanup Failed to remove some directories [
6367 warn cleanup   [
6367 warn cleanup     '\\?\C:\vjs\t4\node_modules\husky',
6367 warn cleanup     [Error: EBUSY: resource busy or locked, rmdir 'C:vjst4node_moduleshusky'] {
6367 warn cleanup       errno: -4082,
6367 warn cleanup       code: 'EBUSY',
6367 warn cleanup       syscall: 'rmdir',
6367 warn cleanup       path: 'C:\vjs\t4\node_modules\husky'
6367 warn cleanup     }
6367 warn cleanup   ],
6367 warn cleanup   [
6367 warn cleanup     '\\?\C:\vjs\t4\node_modules\listr2',
6367 warn cleanup     [Error: EPERM: operation not permitted, rmdir 'C:vjst4node_moduleslistr2node_modulesrxjsinternalobservable'] {
6367 warn cleanup       errno: -4048,
6367 warn cleanup       code: 'EPERM',
6367 warn cleanup       syscall: 'rmdir',
6367 warn cleanup       path: 'C:\vjs\t4\node_modules\listr2\node_modules\rxjs\internal\observable'
6367 warn cleanup     }
6367 warn cleanup   ],
6367 warn cleanup   [
6367 warn cleanup     '\\?\C:\vjs\t4\node_modules',
6367 warn cleanup     [Error: EPERM: operation not permitted, rmdir 'C:vjst4node_modulesm3u8-parsernode_modules@videojsvhs-utilstestfixturesformatsts'] {
6367 warn cleanup       errno: -4048,
6367 warn cleanup       code: 'EPERM',
6367 warn cleanup       syscall: 'rmdir',
6367 warn cleanup       path: 'C:\vjs\t4\node_modules\m3u8-parser\node_modules\@videojs\vhs-utils\test\fixtures\formats\ts'
6367 warn cleanup     }
6367 warn cleanup   ]
6367 warn cleanup ]
6368 verbose stack Error: command failed
6368 verbose stack     at promiseSpawn (C:Program Filesnodejsnode_modulesnpmnode_modules@npmclipromise-spawnlibindex.js:22:22)
6368 verbose stack     at spawnWithShell (C:Program Filesnodejsnode_modulesnpmnode_modules@npmclipromise-spawnlibindex.js:124:10)
6368 verbose stack     at promiseSpawn (C:Program Filesnodejsnode_modulesnpmnode_modules@npmclipromise-spawnlibindex.js:12:12)
6368 verbose stack     at runScriptPkg (C:Program Filesnodejsnode_modulesnpmnode_modules@npmclirun-scriptlibrun-script-pkg.js:77:13)
6368 verbose stack     at runScript (C:Program Filesnodejsnode_modulesnpmnode_modules@npmclirun-scriptlibrun-script.js:9:12)
6368 verbose stack     at C:Program Filesnodejsnode_modulesnpmnode_modules@npmcliarboristlibarboristrebuild.js:329:17
6368 verbose stack     at run (C:Program Filesnodejsnode_modulesnpmnode_modulespromise-call-limitdistcommonjsindex.js:67:22)
6368 verbose stack     at C:Program Filesnodejsnode_modulesnpmnode_modulespromise-call-limitdistcommonjsindex.js:84:9
6368 verbose stack     at new Promise (<anonymous>)
6368 verbose stack     at callLimit (C:Program Filesnodejsnode_modulesnpmnode_modulespromise-call-limitdistcommonjsindex.js:35:69)
6369 verbose pkgid [email protected]
6370 error code 1
6371 error path C:vjst4node_modulesnpm-merge-driver-install
6372 error command failed
6373 error command C:WINDOWSsystem32cmd.exe /d /s /c node src/install.js
6374 error C:vjst4node_modulesnpm-merge-driver-installsrcget-root.js:8
6374 error   const rootDir = gitRootResult.stdout.toString().trim();
6374 error                                        ^
6374 error
6374 error TypeError: Cannot read properties of undefined (reading 'toString')
6374 error     at getRoot (C:vjst4node_modulesnpm-merge-driver-installsrcget-root.js:8:40)
6374 error     at Object.<anonymous> (C:vjst4node_modulesnpm-merge-driver-installsrcinstall.js:7:41)
6374 error     at Module._compile (node:internal/modules/cjs/loader:1562:14)
6374 error     at Object..js (node:internal/modules/cjs/loader:1699:10)
6374 error     at Module.load (node:internal/modules/cjs/loader:1313:32)
6374 error     at Function._load (node:internal/modules/cjs/loader:1123:12)
6374 error     at TracingChannel.traceSync (node:diagnostics_channel:322:14)
6374 error     at wrapModuleLoad (node:internal/modules/cjs/loader:217:24)
6374 error     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:170:5)
6374 error     at node:internal/main/run_main_module:36:49
6374 error
6374 error Node.js v22.13.0
6375 silly unfinished npm timer reify 1745248985517
6376 silly unfinished npm timer reify:build 1745283537036
6377 silly unfinished npm timer build 1745283537039
6378 silly unfinished npm timer build:deps 1745283537039
6379 silly unfinished npm timer build:run:install 1745283537526
6380 silly unfinished npm timer build:run:install:node_modules/npm-merge-driver-install 1745283537663
6381 verbose cwd C:vjst4
6382 verbose os Windows_NT 10.0.18363
6383 verbose node v22.13.0
6384 verbose npm  v10.9.2
6385 verbose exit 1
6386 verbose code 1
6387 error A complete log of this run can be found in: C:UsersUser NameAppDataLocalnpm-cache_logs2025-04-21T15_22_50_979Z-debug-0.log

I tried with different folder locations, multiple times, with admin cmd. But didn’t work.

Even tried with cleaning npm cache. It didn’t work either.

How does JavaScript event delegation improve performance in large-scale DOM structures?

I’ve read that using event delegation by attaching a single event listener to a parent element is more efficient than adding multiple listeners to child elements.

However, in a real-world scenario with dynamic DOM updates and hundreds of elements, how significant is the performance gain?

Also, are there any caveats or edge cases (like event bubbling limitations) I should be aware of when using delegation on deeply nested elements?

Cannot read properties of undefined (reading ‘__wbindgen_free’) in calling rust function

I am using Rust inside angular as wsam . Installed wsam package cargo install wasm-pack and then created Rust Project using cargo new --lib my-rust-wasm this is my src/lib.rs

     use wasm_bindgen::prelude::*;

     #[wasm_bindgen]
     pub fn greet() -> String {
     "Hello from Rust!".to_string()
    }

building rust-project using wasm-pack build --target web Now this is my angular appComponent.ts

   import { Component, OnInit } from '@angular/core';
   import { RouterOutlet } from '@angular/router';
   import { greet } from '../assets/pkg/my_rust_wasm.js';
   @Component({
     selector: 'app-root',
     imports: [RouterOutlet],
     templateUrl: './app.component.html',
     styleUrl: './app.component.css'
    })
   export class AppComponent implements OnInit {
    async ngOnInit() {
     console.log(greet());
}

   private loadWasmModule(path: string): Promise<any> {
     return import(path);
  }
}

HTML5 Canvas (with multiple SVG files drawn to the canvas) to PNG is not displaying the SVG files; however PNG is not entirely blank? [duplicate]

I’m working on a project that draws repeatedly to an HTML Canvas using a combination of the lineTo and drawImage methods. As far as I can tell, the actual production of the Canvas works as intended. (Not all tiles are intended to be populated, so the below image is an accurate translation from the text file into a visual representation of it.)

a 5×4 tile grid, each tile is 120px in size. SVG images are placed in some (but not all) tiles

The first segment of code I’ll share acts as something of a driver for the rest of the functionality. Essentially, a local text file (formatted according to specifics outlined elsewhere) is opened, read from to populate two vectors, and those vectors accessed by drawGrid() and tileParse().

The reader:

document
    .getElementById('FileInput')
    .addEventListener('change', function (event) {
        let file = event.target.files[0];
        let reader = new FileReader();

        reader.onload = function (event) {
            read(event);
            drawGrid(tilesWidth,tilesHeight);
            tileParse();

            //once map is drawn, convert to image for display
            //attempts have gone here, removed for legibility and elaboration further down
        };

        reader.onerror = (event) => alert(event.error.name);
        reader.readAsText(file);
    });

This draws a grid to the canvas:

function drawGrid(width,height){
    canvas = document.getElementById("canvas");
    canvas.width = width + 20;
    canvas.height = height + 20;

    if (canvas.getContext) {
      const ctxt = canvas.getContext("2d");
      ctxt.save();
      ctxt.beginPath();

      ctxt.strokeStyle = "black";

      var pad = 10; //padding
      //adjust width and height to account for external grid padding

      for(var x = 0; x <= width; x += 120){
        ctxt.moveTo(0.5 + x + pad, pad);
        ctxt.lineTo(0.5 + x + pad, height+pad);
        //ctxt.stroke();
      }

      for (var y = 0; y <=height; y+=120){
        ctxt.moveTo(pad, 0.5 + y + pad);
        ctxt.lineTo(width + pad, 0.5 + y + pad);
        //ctxt.stroke();
      }
      ctxt.stroke();
      ctxt.closePath();

      tileParse();
    }
}

This parses the vectors to add tiles

function tileParse(){
    for (let row = 0; row < tilesArray.length ; row++) {
        for (let col = 0; col < tilesArray[row].length ; col++) {
            let type = tilesArray[row][col][0];
            let extremeness = tilesArray[row][col][1];

            switch(type) {
                case 'R':
                    drawRiver(row,col, extremeness);
                    break;
                case 'M':
                    drawMountain(row,col, extremeness);
                    break;
                case 'V':
                    drawValley(row,col, extremeness);
                    break;
                case 'C':
                    drawSettlement(row,col, extremeness);
                    break;
                case 'F':
                    drawForest(row,col, extremeness);
                    break;
                default:
                    //leave blank
            }
        }
    }
}

And this is one of (the drawRiver() method) the methods called within the tile parser, for reference. All the methods are very very similarly structured, just with changes in line with the different types (Mountain instead of River, for instance).

function drawRiver(tileRow, tileCol, extremeness){
  const canvas = document.getElementById("canvas");
  if (canvas.getContext) {
    const ctxt = canvas.getContext("2d");
    var image = new Image(120,120);
    image.crossOrigin="anonymous";

    switch(extremeness){
      case '1':
        image.src = 'assets/rivers/River1.svg';
        break;
      case '2':
        image.src = 'assets/rivers/River2.svg';
        break;
      case '3':
        image.src = 'assets/rivers/River3.svg';
        break;
      case '4':
        image.src = 'assets/rivers/River4.svg';
        break;
      case '5':
        image.src = 'assets/rivers/River5.svg';
        break;
      default:
        //use original tile as default
        image.src = 'assets/rivers/River.svg';
    }

    image.onload = () => {
      startX = (tileCol*120)+10;
      startY = (tileRow*120)+10;

      ctxt.drawImage(image, startX, startY, image.width, image.height);
    }
    
  }
}

All of this background is because when I attempt to convert the HTML Canvas into a PNG (for display and downloading, but I haven’t implemented any attempts at downloading functionality), the grid (put on the canvas with lineTo()) displays, but none of the SVGs have captured. The below image is a side-by-side of the HTML canvas and the PNG that is currently captured by my code.

a side-by-side comparison of the canvas and the captured png. the png only shows the grid, without any of the svg images

I want to generate a png that captures everything that was added to the canvas. So that side-by-side comparison, if the project were working as intented, should show two elements that look identical when displayed. (No visual differences, that is.)

Note: the SVG files being accessed are stored locally on my computer, and are stored in an assets folder within the GitHub repo that I’m pushing to, so there shouldn’t(?) be any external origin issues with the files.

I have attempted the following attempts at implementation, the first two of which were extracted from this question: Capture HTML canvas as GIF/JPG/PNG/PDF?

const canvas = document.getElementById("canvas");
const url = canvas.toDataURL();
console.log(url);
document.getElementById('finMap').src = url;
canvas.toBlob((blob) => {
            const url = URL.createObjectURL(blob);
            document.getElementById('finMap').src = url;
            })

Both of these techniques, implemented within the reader (the first code snippet I shared), produced the png that only had the grid on it.

This following technique utilizes hongru’s Canvas2Image, but I haven’t been able to get it to work. It throws the following error: InvalidStateError: CanvasRenderingContext2D.drawImage: Canvas exceeds max size.

            import("./canvas2image").then((convertToPNG) => {
            console.log(Canvas2Image.convertToPNG(canvas, tilesWidth*120, tilesHeight*120));
            })

Everything that I’ve read suggests that one of these methods should have worked, or I should have been generating an entirely blank PNG. I can’t figure out where in my implementation things are going awry to be able to further drill down in my troubleshooting.

Why do I have to set up an infinite loop on an Event Source in PHP?

I’m trying to learn about how Event sources work in a JS-PHP environment.

In my project directory, I have 3 mains files:

script.js 
/agents/handler.php
/agents/transmitter.php

The script.js will post a XMLHttpRequest to the handler.php, and then the script.js will immediately open up a connection to transmitter.php.

Here is the relevant code in the script.js

function postToHandler(){
 
    let xhr = new XMLHttpRequest();
    xhr.open("POST", "./agents/handler.php");

    let form = new FormData();
    form.append('listen', "mockData");

    xhr.send(form);

    //Connecting to transmitter
    eventSrc = new EventSource("./agents/transmitter.php");
    eventSrc.addEventListener("ping", displayData);
}

And here’s my handler.php

include "./transmitter.php";

if (!empty($_POST['listen'])) {
    
    for($x=0; $x<10; $x++){
        sleep(1);
        $result = getResult();

        transmitVal($result);
    }
}

function getResult(){
    return rand(10, 100);
}

And here’s my transmitter.php

header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
ob_end_flush();

function transmitVal($param){
    echo "event: pingn";
    echo "data: ".$param."nn"; 
}

So what I’m trying to do is call the transmitter’s function from inside my handler file. And hopefully that transmitter will echo out those statements to the connection that was opened by the script.js.

However when I try this, it doesn’t seem to work. My script.js is not receiving any data from transmitter.

What I also don’t understand is why do I have to enclose all the code in my transmitter file with while(true)? Every tutorial online does that but I cannot figure out why.

If I am calling the transmitter’s function from inside my handler……why is a loop required?