How to trigger react-router-dom prompt from a function

On page change or reload or close, react-router-dom prompt is displaying; however, in my page I am using Material UI tabs and I want the prompt to display on tab change as well.

This is the code for my prompt.

    <Prompt
      when={valueChanged}
      message={"Are you sure you want to leave?"}
    />

The prompt only displays if I change in the route or close the browser or reload, but how can I make it display without having to change the route (when a change happens on the same page).

moving between section page using next and previous button in javascript

In the same page i have multiple section.

One section will be show and this will happen using a class active.

In the same page i have li buttons 1, 2 and 3 when i click on one of them the section related appear and the old one disappear for that i’m using javascript to do it.

Also in the same page i have a next and previous button when i click on the next button i should appear the next section and disapear the old one.

And also the relate li to the section should have the class active the same thing for the previous when i click on it i should go to the old section and disappear the current one and the li number should be active.

And when i’m in the first section the previous button should be disapear and when i’m in the last section the next button should be disapear

How can i do the next and previous buttons in this way using javascrip?

let tab = document.querySelector(".nav li");
let tabs = document.querySelectorAll(".nav li");
let tabsArray = Array.from(tabs);
let section = document.querySelectorAll(".section");
let sectionArray = Array.from(section);
let nextButton = document.querySelector(".btn-next");
let prevButton = document.querySelector(".btn-prev");
let current = 0;

tabsArray.forEach((ele) => {
    ele.addEventListener("click", function (e) {
        tabsArray.forEach((ele) => {
            ele.classList.remove("active");
        });
        e.currentTarget.classList.add("active");
        
        sectionArray.forEach((sec) => {
            sec.classList.remove("active");
        });
        document.querySelector('#' + e.currentTarget.dataset.cont).classList.add("active");
    });
});
.section {
display: none;
}

.section.active{
display: block;
}

ul {
list-style: none;
margin:0;
padding: 0;
display: flex;
align-items: center;
}

ul li {
background: #ccc;
padding: 10px 15px;
margin-left: 6px;
border-radius: 50%;
cursor: pointer;
opacity: .5;
}

ul li.active{
opacity: 1 !important;
}

.next,
.previous {
padding: 15px 10px;
border-radius: 6px;
background: deepskyblue;
color: white;
border:0;
outline: none;
cursor: pointer;
width: 100px;
}
<ul class="nav">
<li class="active" data-cont="r1">1</li>
<li data-cont="r2">2</li>
<li data-cont="r3">3</li>
</ul>


<section id="r1" class="section section-one active">
<h2>section 1</h2>
</section>
<section id="r2" class="section section-two">
<h2>section 2</h2>
</section>
<section id="r3" class="section section-three">
<h2>section 3</h2>
</section>

<button class="next" id="next">Next</button>
<button class="previous" id="previous">Previous</button>

solana candy machine – is it possible to know if user click approve in transaction

I am using the solana candy-machine for minting the nft.

When i call smart contract function in javascript

import * as anchor from "@project-serum/anchor";

let program = new anchor.Program(idl, programId, provider);
let result = await program.rpc.someFunc(); //here is the smart contract function

browser will show pop up for you to approve the transaction.
is There any way to know if user click cancel or approve?

In ethereum, it has something like below:

          .on("transactionHash", function(hash) {
                …
          })
          .on("error", function(error, receipt) {
        …
          });

is it possible to do it in candy machine? I want to do something after user click approved in transaction

how to export a .js file with multiple arrays as module

I have 2 arrays inside data.js which looks like this-

I have a data.js file that has 2 arrays like this-

I have another file test.js where I want to import data.js as module like this –

const data = require('./data.js')

and then access each array in this format-

data.girlsDataWeightAge[0]
data.boysDataWeightAge[0]

currently I am exporting each array like this –

export const NameOfArray= []

amd importing each array separately like this-

 import {girlsDataWeightAge} from './data.js';
 import {girlsDataWeightAge} from './data.js';

but I dont want to import them separately because I am going to pass the data through some functions and need to access it only the way I have specified above.

Compile js in tsconfig

I am working on a project that creates a web extension. Normally, I write my code with ts.
I want to add my js file in my project. I am getting an error “only amd and system modules aare supported alongside –outfile”

{
  "compilerOptions": {
    "jsx": "react",
    "module": "es6",
    "target": "es6",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "outDir": "./dist",
    "allowJs": true,

    "outFile": "./dist/background.js"
  },
  "include": ["src/**/.ts", "src/**/*.tsx"],
  "exclude": ["node_modules"]
}

Object.keys not printing properly in my code

I am trying to get only keys from the object, but I am getting 0 1 2 3 as output.

Below is my code

data = {"property" : "{"animalID": "12345", "animalNumber" : "789", "type" : "mamal"}

onCLick() {
  const dataOne = (JSON.parse(JSON.stringify(this.data)));
  console.log("data", Object.keys(dataOne.property));
}

Below is the current output, which is wrong.

data (61) ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60']

Trying to achieve something like this

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]

Why async/await and then produce different results

I’m just asking this question to clarify and get a better understanding at javascript promises. The following two codes look very similar to me, but why both gives different results. Also how to get the result of async/await function in .then way. Thanks.

async/await

const getFieldValue = async (collection, userid) => {
  let response;

  const querySnapshot = await firestore()
    .collection(collection)
    .where("userid", "==", userid)
    .get();
  querySnapshot.forEach((doc) => {
    const { name } = doc.data();
    response = name;
  });

  return response;
};
async function fetchData() {
  const name = await getFieldValue("Users", userid);
  console.log("name", name);
}
fetchData();

.then

const getFieldValue = (collection, userid) => {
  let response;

  firestore()
    .collection(collection)
    .where("userid", "==", userid)
    .get()
    .then((querySnapshot) => {
      querySnapshot.docs.find((doc) => {
        const { name } = doc.data();
        response = name;
      });
    })
    .catch((e) => console.log(e));

  return response;
};
const name = getFieldValue("Users", userid);
console.log("name", name);

async/await returns correct name and .then returns undefined

Handle image before adding file in filepond

How can i handle image before adding file in filepond? I want something like this:

pond.on('beforeadd', (file) => {
    const newFile = addWatermark(file);
    return newFile;
});

I know i can do this with transform plugin but it is firing only while image is processing. I want to add edited file directly preview.

Cropped svg in downloading pdf using html2pdf javascript?

svg it is rendered perfectly in HTML, but when I download it is not rendering properly. why?

in html
enter image description here

in PDF
enter image description here

Code

function saveAsPDF() {
            var element = document.getElementById('printableArea');
            var opt = {
                margin: 0.3,
                filename: 'download.pdf',
                image: {type: 'jpeg', quality: 1},
                html2canvas: {scale: 4, dpi: 72, letterRendering: true},
                jsPDF: {unit: 'in', format: 'A2'},
                html2canvas: {
                    onclone: (element) => {
                        const svgElements = Array.from(element.querySelectorAll('svg'));
                        svgElements.forEach(s => {
                            const bBox = s.getBBox();
                            s.setAttribute("x", bBox.x);
                            s.setAttribute("y", bBox.y);
                            s.setAttribute("width", bBox.width);
                            s.setAttribute("height", bBox.height);
                        })
                    }
                }
            };
            html2pdf().set(opt).from(element).save();
        }
        

why javascript is crash-safe and type-safe?

in this paper: https://ieeexplore.ieee.org/document/7958598, the authors said that javascript is crash-safe and type-safe. they said crash-safe means it will never hard crash. what is the difference of crash and hard crash in javascript? what does hard crash mean in javascript? why javascript is crash-safe?
also in javascript 2+”2″ can be done without any trouble. so why javascript is type-safe? I always know javascript as type-unsafe?

Calling class method in jquery

Hey im trying to build a simple inventory program. I have class like this :

    <?php
    class category
    {
    public static $catoptSupplies=array(
        "Cleaning Supplies",
        "Guest Supplies",
        "Printing Supplies"
        );
    public static function loopcat3()
        {
            $loop3=category::$catoptSupplies;
            $spnum=1;
            foreach ($loop3 as $prnloop3) 
            {   
                echo "<option value='spcat$spnum'>$prnloop3</option>";
                $spnum++;

            }
        }

    }

?>

now i want to append rows in my table which contain select option like this:

 <script>
    $(document).ready(function(){
        var count=1;
        $('#addMsGDRow').click( function(){
            count = count+1;
            var addMsGDRow ='<tr id="row'+count+'">
                                    <td>
                                        <select style="font-size: 12px; width: 83%; text-align: center;">
                                            <option>--Choose Category--</option>
                                            <?php echo category::loopcat3(); ?>
                                        </select>
                                    </td>
                                    <td>
                                        <select style="font-size: 12px;  text-align: center;">
                                            <option>Unit</option>
                                            <option>Meter</option>
                                            <option>Pcs</option>
                                        </select>
                                    </td>
                                    <td><input type="text" name="" style="width: 70px;"></td>
                                    <td><input type="text" name="" style="width: 140px;"></td>
                                    <td>
                                        <textarea style="width: 121px; height: 43px;"></textarea>
                                    </td>
                           <td><input type="number" name="" style="width: 75px;" min="0"></td>
                           <td><input type="number" name="" min="0" style="width: 100px;"></td>
                           <td><input type="number" name="" min="0" style="width:140px;"></td>
                           <td><button type="button" name="remove" data-row="row'+count+'" class="btn btn-danger btn-xs removemsgd">-</button></td>
                                </tr>';
            $('#tableMsGoods').append(addMsGDRow);
        });
        $(document).on('click', '.removemsgd', function(){

          var delete_row=$(this).data("row");
          $('#'+delete_row).remove();

      }); 
    });
</script>

but new row wont added if call my class using normal php line. It does however add a new row if i remove the php line. So, how can i call my class in jquery ?

How to stop chrome from upgrading websockets from WS to WSS when the websocket object is created on an HTTPS page

I made a real browser port of minecraft here that is multiplayer only, it is based on websockets.

https://g.eags.us/eaglercraft/

I want the game on this page to be able to connect to servers using both the WS and WSS websocket protocol, so buying web SSL certificates is not mandatory for the people who are just trying to set up small private servers to use to play this game on from school computers or something. Both my origin server and cloudflare are currently configured to be strictly HTTPS only and you cannot normally initialize an insecure WS websocket from a secure HTTPS page, meaning anyone trying to play the game on their own server off of my ‘official’ link will need an SSL certificate and a WSS URI.

I have added the content-security-policy: upgrade-insecure-requests header to the link I posted above. I am under the impression that this enables regular insecure HTTP/WS connections to be made on the page even if the page was loaded via HTTPS but it doesn’t appear to work. When I create a WebSocket object in chrome devtools console of this page and tried connecting it to a WS URI, the network tab shows that the actual request used by the object had the WS in the URI replaced with WSS even though the URI I typed was WS.

How do I disable all this behavior and just perform the websocket request as-is

IndexedDB transactions to synchronize two tabs

I’m using IndexedDB as a data store for an application. Application state is saved to IDB on blur of certain fields. I would like for other browser tabs that have the same application open to fetch and display the most recent data on focus.

This seems to work fine in practice and I’m unable to break it, but I’d like to verify it. I can imagine a problem where if a user enters data in a field, then immediately clicks to a different window of the same application view. The first window will save data to IDB on blur, but the focus event of the other window could fire before that save has fully gone through.

I’m wondering whether using a transaction for both the write and the read would guard against that problem? Reading the IDB spec, I think this part seems to indicate so but I’d love for someone to validate my logic:

Any transaction created after a read/write transaction sees the changes written by the read/write transaction. For example, if a read/write transaction A, is created, and later another transaction B, is created, and the two transactions have overlapping scopes, then transaction B sees any changes made to any object stores that are part of that overlapping scope. This also means that transaction B does not have access to any object stores in that overlapping scope until transaction A is finished.

Page is flickering while parsing HTML in react component using shadow root

I am parsing HTML string to react component.
when I reload the page then first time response came from server and page render perfectly.
Now client side rendering start working and page become blank(flicker) for 1 sec. then again page rerender.

my HTML string size is around 300kb.

How I can overcome this flickering page between SSR and CSR?

For creating HTML string to Component page I am using following NPM package

  • react-shadow

  • react-html-parser

  • htmlparser2

    <root.div
      className='htmlTemplate'
      mode={elem ? 'open' : 'closed'}
    >
         <style>{globalCss}</style>
         <div ref={this.setRef} className={className} {...rest}>
           {ReactHtmlParser(templateParser(template, templateData), {
             decodeEntities: decodeTemplate,
             transform: this.transform
           })}
         </div>
       </root.div>
    

Server side I am using ReactDOM.renderToNodeStream