Updating state is rerendering components which don’t rely on this state

I have this very minimal app. It consist of one input element and a table. When pressing on a cell in the table, the input element shows what cell was pressed in the table.
However, I noticed that it takes surprisingly long (0.3s) to show the selected cell in the input element. I then did some profiling, and console.logging, and this was the output:

enter image description here
enter image description here

I’m still very much a beginner in React, and would like to know what design patterns I’m overseeing for functionality like this. I don’t understand why the entire app is re-rendered (at least in the virtual DOM), even though only a small section of it (the <ShowSelectedCell/>) should change.

Minimal example:
Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Tooltip, TextField } from '@mui/material';
import { useState } from 'react'

const ShowSelectedCell = ({ cell }) => {
    return (
        <TextField disabled value={cell} />
    );
}

const SelectCell = ({ cells, onCellClick }) => {
    return (
        <table >
            <tbody>
                {console.log('rendering SelectCell')}
                {cells.map(function (template_name, r) {
                    return (
                        <tr key={r}>
                            {template_name.map(function (item, c) {
                                return (
                                    <Tooltip disableInteractive key={`${r} ${c} tooltip`} title={`${r} ${c}`} placement="bottom-start">
                                        <td style={{ "border": "solid" }}
                                            onClick={() => { onCellClick(r, c) }}
                                            key={`${r} ${c} button`}>
                                            {`${r} ${c}`}
                                        </td>
                                    </Tooltip>
                                );
                            })}
                        </tr>
                    );
                })}
            </tbody>
        </table>
    );
}

const App = () => {
    const [cells, setCells] = useState(Array(30).fill().map(() => Array(25).fill(null)))
    const [cell, setCell] = useState('')

    const onCellClick = (r, c) => {
        setCell([r, c])
        console.log(`${r}, ${c}`)
    }

    return (
        <div className='container'>
            {console.log('rerendering app')}
            <ShowSelectedCell cell={cell} />
            <SelectCell onCellClick={onCellClick} cells={cells} />
        </div>
    )
}

ReactDOM.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>,
    document.getElementById('root')
);

Index.html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />

    <title>React App</title>
</head>

<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
</body>

</html>

Get the method and url from an XMLHttpRequest instance

Suppose you do

const xhr = new XMLHttpRequest();
xhr.open('GET', '/test');
xhr.send();

The question is, is there a way, to extract url and method from that xhr object?

For example, when the response is received you can get the url: xhr.responseURL. But can I get the method too (there is no xhr.responseMethod)

In my case I cannot patch the XMLHttpRequest prototype and store these values, I have to deal with the instance only. Any suggestions?

running js script from python

I am trying to run this js code in python. Is it possible to do it ?

import { recoverPersonalSignature } from 'eth-sig-util';
import { bufferToHex } from 'ethereumjs-util';

const msg = `I am signing my one-time nonce: ${user.nonce}`;

            // We now are in possession of msg, publicAddress and signature. We
            // will use a helper from eth-sig-util to extract the address from the signature
            const msgBufferHex = bufferToHex(Buffer.from(msg, 'utf8'));
            const address = recoverPersonalSignature({
                data: msgBufferHex,
                sig: signature,
            });

            // The signature verification is successful if the address found with
            // sigUtil.recoverPersonalSignature matches the initial publicAddress
            return address;

Download a Blob in PNG Format

First of all, I hope you had a good Christmas holiday!

I specify that I am a beginner in JS, hence my possible eccentric attempts to try to download my Blob in PNG.

My problem is to export all the graphic content of a DIV in pdf or image format by clicking on a button(the class name of the div is always the same)

After some research I understood that I had to convert the div to canva to be able to download it.
I tried to adapt the code from this post:
How to take screenshot of a div with JavaScript?

But when I click on the button nothing happens despite my various modifications and tests …

Here is a preview of my code :

<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Export Visualisation QS</title>
</head>
<body>
    <div class="qvt-sheet-container">
        <h1>EXPORT PNG</h1> 
        <img src="Logo-Qlik.png">
    </div>
    <a id="link"><button id="btn-export-qs">Export PNG</button></a>
</body>

<script language="JavaScript" type="text/javascript" src="jquery-3.6.0.min.js">
var a = document.getElementById("link");
function export_feuille() {
    $("#btn-export-qs").click(function() {
        html2canvas($(".qvt-sheet-container"), {
            onrendered: function(canvas) {
                //theCanvas = canvas;
                canvas.toBlob(function(blob) {
                    //saveAs(blob, "Dashboard.png");
                    url = window.URL.createObjectURL(blob);
                    a.href = url;
                    a.download = "export_qs.png";
                    a.click();
                    window.URL.revokeObjectURL(url);
                });
            }
        });
    });
};

document.getElementById("btn-export-qs").addEventListener ("click", export_feuille, false);

</script>
</html>

If anyone could educate me on what is wrong or point me in a direction I would be very grateful 🙂

How to create area chart with range slider in Angular using ChartJs v3.x.x

I want to implement area chart with a range slider above it in Angular v13. On dragging the slider, the appropriate value should get populated in the the table below. I don’t know if it’s even possible with ChartJs v3, if it’s not then I’m open to switch to some other open source free chart library. Could anyone please help me out here?

This is close to what I want to achieve.

this is close to what I want to achieve

axios post request does not redirect to wanted page

In my script, I intend to proxy my requests using hide.me.
When I try replicating the post request using axios, it redirects me to the home page, instead of the required page.
Also tried using python requests, and it works just fine. Node-fetch and axios-http fail.

My current code is below:

const qs = require('qs');
const axios = require('axios');
const proxySiteMap = async () => {
    let proxy_locations = ["de", "nl", "fi"]
    let url = process.env.PRODUCT_SITEMAP_URL;
    let proxy_host = process.env.PROXY_URI
    let loc = randomChoice(proxy_locations);
    let proxy_url = `https://${loc}.${proxy_host}`
    console.log(proxy_url);
    let config = {
        url: proxy_url,
        method: "POST",
        headers: {
            'authority': `${loc}.hideproxy.me`,
            'origin': 'https://hide.me',
            'content-type': 'application/x-www-form-urlencoded',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'referer': 'https://hide.me/',
            'accept-language': 'en-US,en;q=0.9,sv;q=0.8,hy;q=0.7',
        },
        params: {
            action: 'update'
        },
        data: qs.stringify({
            u: url,
        })
    };

    let html;
    let response;
    let links = [];

    try{
        response = await axios(config);
        html = response.data;
        console.log(response.config)
    } catch(error){
        console.log(`Error while fetching sitemap. Response code ${error}`)
    }

Relatively new to javascript/nodejs don’t know what I’m doing wrong

How to save checkbox value for each question with textbox value in JavaScript?

I am creating an HTML questionnaire and getting all data from API calls. I have set data into an array and displayed them. Now I need to save the questionnaire DATA to the database. I have questions with checkbox answers. There is a checkbox for every question that has a value called ‘other’. If the user clicks on that checkbox it will display a textbox. I need to add these checkboxes answers to an object array. Like below,

{QType: 'Questionnaire', QuesID: '1', OpId: '1', option: '1'}
{QType: 'Questionnaire', QuesID: '1', OpId: '2', option: '2'}
{QType: 'Questionnaire', QuesID: '2', OpId: '6', option: '6'}
{QType: 'Questionnaire', QuesID: '2', OpId: '7', option: '7'}

And also if the user checks the other option, the textbox value also concatenates with the idsquestion.

{QType: 'Questionnaire', QuesID: '2', OpId: '8+'this is textbox value'+', option: '8'}

This is what I tried;

let Questions = [
    { idsquestion: "1", questionname: "Where do you use internet?" },
    { idsquestion: "2", questionname: "What type of credit card do you have?" },
];
let Ans = [
    { idqoption: "1", idsquestion: "1", qoption: "Home" },
    { idqoption: "2", idsquestion: "1", qoption: "School" },
    { idqoption: "3", idsquestion: "1", qoption: "Office" },
    { idqoption: "4", idsquestion: "1", qoption: "Other" },
    { idqoption: "5", idsquestion: "2", qoption: "VISA" },
    { idqoption: "6", idsquestion: "2", qoption: "Mastercard" },
    { idqoption: "7", idsquestion: "2", qoption: "American Express" },
    { idqoption: "8", idsquestion: "2", qoption: "Other" },
];

function getData() {
    const parent = document.getElementById("questions-container");
    const frag = document.createDocumentFragment();

    for (const questionObj of Questions) {
        const container = document.createElement("div");
        container.className = "question-list";

        const questionElm = document.createElement("p");
        questionElm.textContent = questionObj.questionname;
        questionElm.className = "question-p";

        container.append(questionElm);

        const ansElm = document.createElement("div");
        ansElm.className = "answer-container";
        ansElm.id = questionObj.idsquestion;

        for (const ansObj of Ans) {
            if (questionObj.idsquestion == ansObj.idsquestion) {
                const checkBoxElm = document.createElement("input");
                checkBoxElm.setAttribute("type", "checkbox");
                checkBoxElm.id = ansObj.idquestionoption;
                checkBoxElm.name = ansObj.idsquestion;
                checkBoxElm.className = "check-box-class";
                checkBoxElm.value = ansObj.qoption;
                checkBoxElm.onclick = () => ansQuestions(checkBoxElm);

                const lblCheckBox = document.createElement("label");
                lblCheckBox.textContent = ansObj.qoption;
                lblCheckBox.className = "lbl-class";
                lblCheckBox.htmlFor = ansObj.idquestionoption;
                lblCheckBox.id = "lbl_" + ansObj.idquestionoption;

                ansElm.append(checkBoxElm, lblCheckBox);

                if (ansObj.qoption == "Other") {
                    const txtBoxElm = document.createElement("input");
                    txtBoxElm.setAttribute("type", "text");
                    txtBoxElm.setAttribute("name", "txt_" + ansObj.idsquestion);
                    txtBoxElm.setAttribute("id", "txt_" + ansObj.idsquestion);
                    txtBoxElm.setAttribute("style", "display:none");
                    ansElm.append(txtBoxElm);
                }
                container.append(ansElm);
            }
        }
        frag.append(container);
    }
    parent.append(frag);
}

function ansQuestions(ansObj) {
    var chkBoxVal = $(ansObj).attr("id");
    var chkBoxVal2 = $(ansObj).attr("value");
    var chkBoxVal3 = $(ansObj).attr("name");
    console.log(chkBoxVal3);

    if (chkBoxVal2 == "Other") {
        var text = document.getElementById("txt_" + chkBoxVal3);
        text.style.display = "block";
        console.log(text);
    } else {
        text.style.display = "none";
    }
}
function saveData() {
    var QType = "Questionnaire";
    var Qobj = { QType: QType, QuesID: QuesID, OpId: OpId, option: option };
}
<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <title></title>
    </head>
    <body onload="javascript:getData()">
        <div id="Review2">
            <div data-role="content">
                <div id="questions-container"></div>
                <div id="button-container">
                    <button onclick="saveData()">Submit</button>
                </div>
            </div>
        </div>
    </body>
</html>

How to make uglify and grunt index all imports and generate one single file

I have just started using grunt and I want it to use combine all files and uglify them.
But my issues is that it combines and uglifys, but it doesn’t remove import statements. (I’m using uglify and concat)

What I want –

// File.js
import something from './something.js';
something.someFunction("hello world");

and

// something.js
export default {
   someFunction: function(msg){console.log(msg)}
}

to

// all.js
var something = {
  someFunction: function(msg){
     console.log(msg)
  }
}
something.someFunction("hello world");

Compressing is not an issue.

How to play audio onload in react using Howler library?

I was trying to figure out why the audio is not running onload of webpage until an event such as mouse click is triggered somewhere on the screen. The audio plays but I want to play the audio as soon as the page loads.

import React, { useEffect } from "react";
import Muse from "./assets/music.mp3";
import { Howl, Howler } from "howler";

function Aud() {
  const sound = new Howl({
    src: Muse,
  });

  useEffect(() => {
    console.log("In useEffect");
    sound.play();
    Howler.volume(0.5);
  }, []);

  return <div></div>;
}

export default Aud;

useEffect executes but for some reason the sound doesn’t play. Any help would be appreciated.

How can I implement deffered deeplinking in Javascript, given I have no idea how’s it done in flutter?

Flutter devs in my team have implemented a traditional deep linking mechanism that shows “continue with app or chrome option” when the app is already installed, otherwise nothing happens. I tried implementing deferred deep linking as shown in the below code as an example, but I need some more reliable implementation.

window.location.href = 'example_app://';

// fire a function if above redirection fails
setTimeout(function() {                
  window.location.href = "https://play.google.com/store/apps/details? 
    id=<app_id>;
}, 5000);

The problem with this is even though I expected href to stop JS execution of the previous page, it doesn’t, and hence code becomes unpredictable.
Is there a way where I can implement deferred deep linking without branch.io or other third-party implementation? And why can it be better to use third-party implementation rather than something made from scratch?

how to implement the logical assignment in destructuring assignment in javascript?

destructuring assignment doesn’t work for the field in one object holds a falsy value, as follow:

let { aaa = 123 } = { aaa: null }
console.log(aaa) // null

so, how to achive ||= in object destructuring assignment to implement such the field’s destructed defalut value ? like this:

let { aaa ||= 123 } = { aaa: null }
console.log(aaa) // 123

// it equals to
// let aaa = ({ aaa: null }).aaa || 123