Getting an error on a react app while using Clerk login. Failed to execute ‘atob’ on ‘Window’: The string to be decoded is not correctly encoded

Error stack

This error pops up when running the react app with clerk login

isomorphicAtob.ts:7 
Uncaught InvalidCharacterError: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
    at isomorphicAtob (isomorphicAtob.ts:7:12)
    at isPublishableKey (keys.ts:77:38)
    at ClerkProviderBase (ClerkProvider.tsx:17:35)
    at renderWithHooks (react-dom.development.js:15486:18)
    at mountIndeterminateComponent (react-dom.development.js:20103:13)
    at beginWork (react-dom.development.js:21626:16)
    at HTMLUnknownElement.callCallback2 (react-dom.development.js:4164:14)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:16)
    at invokeGuardedCallback (react-dom.development.js:4277:31)
    at beginWork$1 (react-dom.development.js:27490:7)

Tried reinstalling node modules folder but still got the same

Getting some special character in pagelength of datatable

I have added pagelength dropdown in same row of export options but now when we click on pagelength dropdown i can see some special character as shown below in picture.

enter image description here

when i inspect it through browser i can see the character is coming from the datatable.css from below css tag

enter image description here

enter image description here

below is javascript

<script>
    $(document).ready( function () {
        $('#fTable').DataTable( {
        data: fData,
        ordering: false,
        lengthChange: false,
        dom: 'Blfrtip',
        lengthMenu: [2, 25, 50, 75, 100],
        buttons: ['csv', 'excel', 'pageLength'],
        columns:[
             <% for (String column : columnsArray) { %>
                {data:'<%= column %>',title:'<%= column %>'},
            <% } %>

        ]
        });
    });
    

</script>

I have tried removing that character from the css but still getting same. can someone please help on this ?

English To Devnagari Words on KeyUp javascript not working

With some google help, I have following javascript to convert English words to devnagari words.

E.g. When user enters word “India” in input field, it should be “इंडिया”.

But don’t getting where is the issue as this js is not working… I am stuck where the issue is..

JS – eng-to-devnagari.js

 // initialize map for basic devnagari characters
 var devnagari = {'a':'अ','aa':'आ','i':'इ','ii':'ई','u':'उ','uu':'ऊ','e':'ए','ai':'ऐ','o':'ओ','au':'औ','k':'क्','ka':'क','kh':'ख्','kha':'ख','g':'ग्','ga':'ग','gh':'घ्','gha':'घ','ch':'च्','cha':'च','chh':'छ्','chha':'छ','j':'ज्','ja':'ज','jh':'झ्','jha':'झ','t':'त्','ta':'त','tha':'थ','th':'थ्','T':'ट्','Ta':'ट','Th':'ठ्','Tha':'ठ','d':'द्','da':'द','D':'ड्','Da':'ड','Dh':'ढ्','Dha':'ढ','dh':'ध्','dha':'ध','n':'न्','na':'न','Ng':'ङ्','Nga':'ङ','N':'ण्','Na':'ण','Yn':'ञ्','Y':'य्','Ya':'य','Yna':'ञ','p':'प्','pa':'प','ph':'फ्','pha':'फ','b':'ब्','ba':'ब','bh':'भ्','bha':'भ','m':'म्','ma':'म','y':'य्','ya':'य','r':'र्','ra':'र','rr':'र्‍','l':'ल्','la':'ल','v':'व्','va':'व','sh':'श्','sha':'श','s':'स्','sa':'स','shh':'ष्','shha':'ष','h':'ह्','ha':'ह','c':'क्','ca':'क','f':'फ्','fa':'फ','q':'क्','qa':'क','w':'व्','wa':'व','x':'ज्','xa':'ज','z':'ज्','za':'ज','O':'ॐ'};

 // initialize sandhi
 var shabda_sandhi = { 'aa':'ा','i':'ि','ii':'ी','u':'ु','uu':'ू','e':'े','ai':'ै','o':'ो','au':'ौ'};

 // separate out vowels and consonants
 var vowel = { 'a':'','i':'','u':'','e':'','o':''};
 var consonant = { 'b':'','c':'','d':'','D':'','f':'','g':'','h':'','j':'','k':'','l':'','m':'','n':'','N':'','p':'','q':'','r':'','s':'','t':'','T':'','Y':'','O':'','v':'','w':'','y':'','x':'','z':'' };

 // numerals
 var numerals = {0:'',1:'',2:'',3:'',4:'',5:'',6:'',7:'',8:'',9:''};

 // initialize special characters (add if not listed below)
 var special_characters = { '`':'','~':'','!':'','@':'','#':'','$':'','%':'','&':'','(':'',')':'','-':'','_':'','=':'','+':'','{':'','}':'','[':'',']':'','\':'','|':'',';':'',':':'','"':'',''':'','<':'','>':'',',':'','.':'','?':'', '/':'','A':'','B':'','C':'','E':'','F':'','G':'','H':'','I':'','J':'','K':'','L':'','M':'','P':'','Q':'','R':'','S':'','U':'','V':'','W':'','X':'','Z':'' }

 // map of arrays

 var mystruct = { 
   a : A=new Array("aa","ai","au","a"),
   b : B=new Array("bh","b","ba","bha"),
   c : C=new Array("chh","ch","cha","c","ca","chha"),
   d : D=new Array("d","da","dh","dha"),
   D : D1=new Array("D","Da","Dh","Dha"),
   e : E=new Array("e"),
   f : F=new Array("f","fa"),
   g : G=new Array("gh","gha","g","ga"),
   h : H=new Array("h","ha"),
   i : I=new Array("ii","i"),
   j : J=new Array("jh","jha","j","ja"),
   k : K=new Array("kh","kha","k","ka"),
   l : L=new Array("l","la"),
   m : M=new Array("m","ma"),
   n : N=new Array("n","na"), 
   N : N1=new Array("N","Na","Ng","Nga"),
   o : O=new Array("o"),
   O : O1=new Array("O"),
   p : P=new Array("ph","pha","p","pa"),
   q : Q=new Array("q","qa"),                   
   r : R=new Array("r","ra","rr"),              
   s : S=new Array("shh","shha","sh","sha","s","sa"),
   t : T=new Array("th","tha","t","ta"),
   T : T1=new Array("T","Ta","Th","Tha"),
   u : U=new Array("uu","u"),
   v : V=new Array("v","va"),
   w : W=new Array("w","wa"),
   x : X=new Array("x","xa"),
   y : Y=new Array("y","ya"),
   Y : Y1=new Array("Y","Ya","Yn","Yna"),
   z : Z=new Array("zh","z","za"),
 };

 var flg = "";
 var result = "";
 var code = "";
 var code_support = "";
 var flag_for_shabda_sandhi = false;
 var toggleon = false;
 var word = "";

//FUNCTION STARTS

 function inputDevnagari( val ){        
  temp_val = val;

  for ( var k = 0; k < temp_val.length; k++ ) {
    
    // checks for 'English Mode'
    if ( enable_Eng( temp_val[k] ) ) continue;      // we don't need to process it
    
    // few special cases
    if ( temp_val[k] == "*" ) { 
            display("ँ");
            continue;
    }
       
    if ( temp_val[k] == "^" ) { 
            display("ं");
            continue;
    }
    
    if ( temp_val[k] == "R" ) { 
            display("ऋ");
            continue;
    }
    
    // in the first case, calls initilize function
    if ( k == 0 ) {
        initialize( temp_val[k] );
    }

    // concatenate to global word varible
    word = word + temp_val[k];
    if ( exception_handling() ) continue;
        
    // special case, spacebar
    if ( temp_val[k] == "u0020" ) {
        temp_val[k] = "u0020";
        spacebarPressed();
        word = "";
        continue;
    }
    
    
    Unicode( temp_val[k] );
}
resetflags();
if ( temp_val.length == 0 ) display("");
}

function resetflags(){
 toggleon = false;
 result = "";
 code = "";
 code_support = "";
 flag_for_shabda_sandhi = false;
 word = "";
}

// initialize function
function initialize(val){   
    flg = mystruct[val[val.length-1]];
}

function changeinDisplay( val ){
    if ( val.length < 2 ) return;
    result = result.substr(0,result.length-2);
}

function changeinDisplay2( val ) {
if ( code[code.length-1] in vowel && code[code.length-2] in consonant ) {
    result = result.substr(0,result.length-1);
}

if  ( ( ( code_support[code_support.length-1] == "i" ) && ( code[code.length-2] == "i" ) ) || ( ( code_support[code_support.length-1] == "u" ) && ( code[code.length-2] == "u" ) ) ){
    result = result.substr(0,result.length-1);
}

}

// special case for spacebase key
function spacebarPressed( ) {
 code_support = "";
 code = "";
 flag_for_shabda_sandhi = false;
 result = result + "u0020";
 document.getElementById('output').value = result;
}

// output function
// change ID as required
function display( result_temp ) {
    result = result + result_temp;
   document.getElementById('output').value = result;
}

// core unicode mapper
function Unicode(val){      
    var last_letter = val[val.length-1];
        
   // checks for numerals or special chars
   if ( last_letter in numerals || last_letter in special_characters ) {
    display( last_letter );
    flg = "e";
    return; 
}

var found = false;
code = code + last_letter;

// basically checks the use of datastructure according to the position of vowel and consonant
// eg 'aa' is आ normally but when we write 'kaa' it should be का
if ( code_support[code_support.length-1] in vowel && last_letter in consonant ) {

    code_support = "";
}

// get character + x [] combination

if ( flag_for_shabda_sandhi == true ) {     
            
    if ( last_letter in vowel ) {
        code_support = code_support + last_letter;
    }
    
    if ( code_support in shabda_sandhi && last_letter in vowel ) {
    
            changeinDisplay2(code_support);
            display( shabda_sandhi[code_support] );
            
            if ( last_letter in vowel && code_support.length < 2 ) {
                flag_for_shabda_sandhi = true;
            }
            else {  
                flag_for_shabda_sandhi = false;
                code_support = "";
            }
            return;
            
    }
        
}

if ( last_letter in consonant )
{
    flag_for_shabda_sandhi = true;
}

// get character from the data structure
for ( var i = 0; i < flg.length; i++ )
{
        if ( flg[i] == code )  {
            found = true;   
            if ( flg[i] == "aa" || flg[i] == "ii" || flg[i] == "uu" ) {
                result = result.substr(0,result.length-1);
            }
            else changeinDisplay(code);
            display( devnagari[code] );
            return;
        }
}

code = last_letter;
flg = mystruct[code];
display( devnagari[code] );        // output in display function
}

// checks if English Mode is enabled or not.
// checks for characters between '<' and '>'
function enable_Eng( val_temp ){
var temp_flag = false;

if ( toggleon && val_temp == '>' ) {
    toggleon = false;
    temp_flag = true;
}

if ( !toggleon ) {
    if ( val_temp == '<' ) {
        toggleon = true;
        temp_flag = true;
    }
}
else if ( toggleon ) {
    display( val_temp );
    temp_flag = true;
}
return temp_flag;
}

// few user defined exceptions for convinience
// add to maps if necessary
function exception_handling(){
var exception = { 'au':'औ','acharya':'आचार्य','airport':'एअरपोर्ट','amrit':'अमृत','char': 'चार','paanch' : 'पाँच','fortystones':'फोर्टिस्टोन्स','kripaya':'कृपया','krishi':'कृषि','krishna' : 'कृष्ण', 'krishnaa' : 'कृष्णा', 'gyan' : 'ज्ञान','shrestha':'श्रेष्ठ','unicode' : 'युनिकोड','united' : 'युनाईटेड' };

temp = result.length-1;

if ( word in exception ) {
    
    while ( result[temp] != "u0020" ) {
        if ( temp == 0 ) {
            temp= -1;
            break;
        }
        temp = temp - 1;
    }   
        
    result = result.substr(0,temp+1);
    display( exception[word] );
    word = "";
    return true;
}
return false;
}

And in HTML Form, Trying as follows

<script src="js/jquery/jquery.js"></script>
<script src="js/eng-to-devnagari.js"></script>

<script>
 $(document).ready(function(){
   $( ".translate" ).on( "keyup", function() {
        var tvalue = $(this).val();
       //alert(tvalue); // Its working...alerting entered input value on keyup
        inputDevnagari(tvalue);
   });
 });
 </script>  

 <label>Full Name</label>
 <input type="text" name="full_name" class="form-control translate" id="full_name" value="<?php if(isset($full_name)){ echo $full_name;}?>" placeholder="Your Full Name In Devnagari">

referencing in nested Objects in Object.assign() method

I’m confused how the object referencing works in the Object.assign() method

let myobj ={
   a : 10, b:20, c:{f:[4569]}, e:[45]
}
let myobj2= Object.assign({},myobj);

myobj2.c.f=[0];
myobj2.e=[0];

console.log(myobj)//{ a: 10, b: 20, c: { f: [ 0 ] }, e: [ 45 ] }
console.log(myobj2)//{ a: 10, b: 20, c: { f: [ 0 ] }, e: [ 0 ] }

Here changing the value of the f reflects both in both of the objects in myobj and myobj2, meanwhile changing the value of e reassigning it, dereference it and changes takes place in the particular object,

I’m expecting same kind of result as happening with the value of e ,as it changes , for each object , while reassigning it , but reassigning the value of f reflects in both of the objects why?

Testing functionality of links with testing-library

This is my first time using the react-testing library. I have a React a custom React component that has a clickable link which will download a file that is stored in a the Redux store. See the code below:

import React from 'react';

//onDownload defined here

const CustomModal = (state) => {
  return (
      <div>
          <a href="#"
            onClick={(event) => {
              event.preventDefault();
              onDownload(state.[file_id]);
            }}
          > {state[file_name}} </a>
         
      </div>
  )
};

I wrote a test that when the link is clicked, the onDownload method will be called. The following code results in error: Received number of calls: 0

import React from 'react';
import { Provider } from 'react-redux';
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
import '@testing-library/jest-dom';

describe('CustomModal', () => {
  let store;

  describe('render', () => {
    beforeEach(() => {

      store = configureStore(
        {
          import: {
            state: {
              file_isas_id: 123456789,
              file_name: 'test_file.xlsx',
            },
          },
        },
      );
      rendered = render(
         <Provider store={store}>
           <CustomModal/>
         </Provider>,
    });

    afterEach(() => {
      cleanup();
    });

    it('should call the onDownload when the download link is clicked', () => {
      const onDownload= jest.fn();
      fireEvent.click(screen.getByText('test_file.xlsx'));
      expect(onDownload).toHaveBeenCalledTimes(1);
    });

Any ideas how to fix? Thank you.

How can I return something from JavaScript to HTML?

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="styles.css" />
        <script src="styles.js"></script>
        <title>Dice Roller</title>
    </head>
    <body>
        <h1>Dice Roller</h1>
        <p>Can't decide on what to eat? Or what to do? Our dice roller is perfect for this.</p>
        <section>
            <button class="roll-button" type="button" onclick="rollDice()">Roll</button>
            <h1>
                <script type="text/javascript">
                var x = rollDice(1, 6);
                output.innerHTML = x;
                </script>
            </h1>
        </section>
    </body>
</html>
function rollDice(a, b) {
    dice = Math.floor(Math.random() * (b + 1)) + a
    return dice
}
body {
    background-color: orange;
    font-family:system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    text-align: center;
    font-size: 150%;
}

.roll-button {
    height: 40px;
    width: 80px;
    font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    font-size: large;
}

I am trying to make a dice function that goes from JavaScript to HTML. How can I do this? I have tried multiple ideas and looked through guides, but they don’t help me at all. Thanks! (new to coding)

Trying to download file from azure blob storage?

I am trying to download files from azure blob storage via restful api.

I have the following snippet which returns a url similar to the one that you can autogenerate through their portal.

async fetchBlobUrl (containerName: string, blobId: string): Promise<string> {
    // Step 1: Prepare the canonical URL path for the blob
    const urlPath = `/${containerName}/${blobId}`

    // Step 2: Set SAS token parameters
    const expiryDate = new Date(new Date().valueOf() + 3600 * 1000) // Expiry is 1 hour from now
    const expiry = expiryDate.toISOString().slice(0, 19) + 'Z' // Format: 2025-01-16T14:33:00Z

    const startDate = new Date() // Start time is now
    const startTime = startDate.toISOString().slice(0, 19) + 'Z' // Format: 2025-01-16T13:33:00Z

    const permissions = 'r' // Read permission
    const sasVersion = '2022-11-02' // SAS API version
    const protocol = 'https' // Protocol should be https
    const resourceType = 'b' // 'b' for blob

    // Step 3: Construct the canonical string to sign (fixing the structure)
    const stringToSign = [
        permissions,       // permissions
        startTime,         // start time
        expiry,            // expiry
        `/blob/${this.accountName}/${containerName}/${blobId}`, // the blob's URL path
        '',                // identifier (optional)
        '',                // IP (optional)
        protocol,          // protocol (https)
        sasVersion,        // SAS version
        resourceType,      // resource type ('b' for blob)
    ].join('n')

    // Step 4: Create a signature using your account key
    const hash = crypto
        .createHmac('sha256', Buffer.from(this.accountKey, 'base64'))
        .update(stringToSign, 'utf8')
        .digest('base64')

    // Step 5: Generate the SAS token by appending the signature
    const sasToken = `sp=${permissions}&st=${startTime}&se=${expiry}&spr=${protocol}&sv=${sasVersion}&sr=${resourceType}&sig=${encodeURIComponent(hash)}`

    // Step 6: Construct the final blob URL
    return Promise.resolve(`https://${this.accountName}.blob.core.windows.net${urlPath}?${sasToken}`)
}

But everytime i test im getting the error:

<AuthenticationErrorDetail>Signature did not match. String to sign used was etc etc etc </AuthenticationErrorDetail>

Using Postman Vault secrets in JWT generation in Pre-request script

In my organization, we have a Postman setup for testing our APIs. Part of the process involves manually signing a JWT in a Pre-request script, using jsrasign and the necessary data, including a Jwtsecret key. It has so far simply been declared in plaintext in the pre-request script, and I am trying to move the sensitive data over to the Postman Vault.

The code looks like this, and works just fine:

var jwtSecret = {
"p":"loremipsum",
"kty":"RSA",
"q":"loremipsum",
"e":"AQAB",
"alg":"RS256"
<more key stuff>
}
<other code>

var signedJWTToken =  KJUR.jws.JWS.sign(null, header, data, jwtSecret);

So I tried changing it to:

var jwtSecret = pm.vault.get("jwtSecret");
....
var signedJWTToken =  KJUR.jws.JWS.sign(null, header, data, jwtSecret);

However, this does not work. The error I get is There was an error in evaluating the Pre-request Script:Error: init failed:TypeError: l.indexOf is not a function

I figured it was not properly parsing the string to a Javascript object, but constructing an object from the JwtSecret did not change the error:

var jwtSecret = pm.vault.get("jwtsecret");
var jwtObject = Object(jwtSecret);
var signedJWTToken =  KJUR.jws.JWS.sign(null, header, data, jwtObject);

It also seems very difficult to debug using console.log because of what seems to be built-in sensitive data protection in Postman.

Anyone with know-how can point me in the right direction?

Form elements can’t be used after submission

The code is here:

https://codepen.io/AthreyuIV/pen/EaYRRrb

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Palindrome Checker</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Rock+Salt&display=swap" rel="stylesheet">
  </head>
  <body>
    <div class="wrapper">
      <div class="checker-container">
        <h1>Palindrome Checker</h1>
        <p>Palindrome</p><p>Checker</op>
        <form name="palindrome" id="palindrome">
           <div class="input-container">
            <input id="text-input" type="text">
            <button id="check-btn" type="submit">Check</button>
           </div>
        </form>  
        <div class="results-container">
        <span id="result"></span>
      </div>
    </div>
    <script type="text/javascript" src="script.js"></script>
  </body>
</html>
const checkButton = document.getElementById("check-btn");

const textInput = document.getElementById("text-input")

const resultText = document.getElementById("result");

const formData = document.getElementById("palindrome");



checkButton.addEventListener("click", () => {

  const cleanString = textInput.value.replace(/W|_/g, "");

  const reverseString = cleanString.split("").reverse().join("");



  if (textInput.value === "") {

    alert("Please input a value.")

  } else if (reverseString.toLowerCase() === cleanString.toLowerCase()) {

    resultText.textContent = `${textInput.value} is a palindrome`;

  } else {

    resultText.textContent = `${textInput.value} is not a palindrome`

  }

  formData.reset()

});

The form elements aren’t behaving right after I reset the form. It seems to become disabled.

I tried using .refocus() and I tried setting textInput.disabled = false; before and after I cleared the form. I tried not even using .reset() and instead setting the textContent to an empty string. I tried making a reset function outside of the eventListener and calling it as a function instead. I’ve tried changing readonly to false.

How to increase the speed of my code execution time javascript [closed]

My code exection time on a average of 12-16 seconds. I need to increase my code execution time to less than 5 seconds. Below is my code.

var usedByOrgVal = "All";

 var arrFinCount = [];

 var arr = [];

 if (usedByOrgVal == "All") {
     arr = ["operational_status!=6", "operational_status!=6^owned_by!=null", "operational_status!=6^u_in_coverage=Yes", "operational_status!=6^u_complete=Yes", "operational_status!=6^u_correct=Yes", "operational_status!=6^u_in_coverage=No", "operational_status!=6^u_complete=No", "operational_status!=6^u_correct=No", "nameISNOTEMPTY^operational_status!=6^u_resp_orgISNOTEMPTY^NQnameISNOTEMPTY^operational_status!=6^u_resp_orgISEMPTY^assetISEMPTY"];
     filterList(arr);
 } else {
     arr = ["operational_status!=6^owned_by.u_program=" + usedByOrgVal, "operational_status!=6^owned_by!=null^owned_by.u_program=" + usedByOrgVal, "operational_status!=6^u_in_coverage=Yes^owned_by.u_program=" + usedByOrgVal, "operational_status!=6^u_complete=Yes^owned_by.u_program=" + usedByOrgVal, "operational_status!=6^u_correct=Yes^owned_by.u_program=" + usedByOrgVal, "operational_status!=6^u_in_coverage=No^owned_by.u_program=" + usedByOrgVal, "operational_status!=6^u_complete=No^owned_by.u_program=" + usedByOrgVal, "operational_status!=6^u_correct=No^owned_by.u_program=" + usedByOrgVal, "nameISNOTEMPTY^operational_status!=6^u_resp_orgISNOTEMPTY^NQnameISNOTEMPTY^operational_status!=6^u_resp_orgISEMPTY^assetISEMPTY^owned_by.u_program=" + usedByOrgVal];
     filterList(arr);
 }

 gs.info("arrFinCount: " + JSON.stringify(arrFinCount));

 function filterList(arrVal) {
     for (var i = 0; i < arrVal.length; i++) {
         var cal = new GlideRecord("cmdb_ci_server");
         cal.addEncodedQuery(arrVal[i]);
         cal.query();
         arrFinCount.push(cal.getRowCount());
     }
 }

 var obj = {
     Ownership: [{
         Value: arrFinCount[1],
         Percentage: isNaN(((arrFinCount[1] / arrFinCount[0]) * 100).toFixed(2)) ? "0.00" : ((arrFinCount[1] / arrFinCount[0]) * 100).toFixed(2),
     }],
     Coverage: [{
         InCoverage: arrFinCount[2],
         OutOfCoverage: arrFinCount[5],
         Percentage: isNaN(((arrFinCount[2] / arrFinCount[0]) * 100).toFixed(2)) ? "0.00" : ((arrFinCount[2] / arrFinCount[0]) * 100).toFixed(2),
     }],
     Completeness: [{
         Complete: arrFinCount[3],
         NotComplete: arrFinCount[6],
         Percentage: isNaN(((arrFinCount[3] / arrFinCount[0]) * 100).toFixed(2)) ? "0.00" : ((arrFinCount[3] / arrFinCount[0]) * 100).toFixed(2),
     }],
     Correctness: [{
         Correct: arrFinCount[4],
         NotCorrect: arrFinCount[7],
         Percentage: isNaN(((arrFinCount[4] / arrFinCount[0]) * 100).toFixed(2)) ? "0.00" : ((arrFinCount[4] / arrFinCount[0]) * 100).toFixed(2),
     }],
     ActiveServerCount: [{
         Count: arrFinCount[8]
     }],
 };

 gs.info("obj:" + JSON.stringify(obj));

 return obj;

I tried adding a callback function sync/async but did not help. Is there any other logic we can bring in to decrease the execution time

React custom hook losing state

So, I’m doing some brushing up on react and I’m making some silly web apps for practice and I’ve run into an issue I can’t seem to figure out here.

I have a custom hook, useGetRequest, that calls an api endpoint provided to it and retrieves data. I have a state variable to track if it is loading, has loaded, or is in error. I pass this loading state to another hook, that then passes it to a component. The problem is, by the time it makes it to the component, the loadingState variable is undefined at every point. I can track that in both hooks, the state is updated but not when the component receives it. Here is my code:

import {useCallback, useState} from "react";
import loadingStatus from "../helpers/loadingStatus"

const useGetRequest = (url) => {
    const [loadingState, setLoadingState] = useState(loadingStatus.isLoading);

    const get = useCallback(async () => {
       console.log(loadingState);
        setLoadingState(loadingStatus.isLoading);
        try {
            const rsp = await fetch(url);
            const result = await rsp.json();
            setLoadingState(loadingStatus.loaded);
            return result;
        } catch {
            setLoadingState(loadingStatus.hasErrored);
        }
    }, [url]);

    return {get, loadingState};
}

export default useGetRequest;

My silly practice app is for TTRPGs just for some context on this useWeapons hook:

import {useEffect, useState} from "react";
import useGetRequest from "@/hooks/useGetRequest";

const useWeapons = () => {
    const [weapons, setWeapons] = useState([]);
    const {get, loadingState } = useGetRequest("/api/weapons");

    useEffect(() => {
        const fetchWeapons =  async () => {
            const weapons = await get();
            console.log(loadingState);
            setWeapons(weapons);
        };
        fetchWeapons();
    }, [get]);

    return [weapons, setWeapons, loadingState];
}

export default useWeapons;

This is the component that creates my table view:

import WeaponRow from "@/components/WeaponRow";
import useWeapons from "@/hooks/useWeapons";
import loadingStatus from "@/helpers/loadingStatus";
import LoadingIndicator from "@/components/loadingIndicator";

const WeaponList = () => {
    const { weapons, setWeapons, loadingState } = useWeapons();

    const addWeapon = () => {
        setWeapons([
            ...weapons,
            {
                id: 2,
                name: "Blaster pistol",
                skill: "Ranged (Light)",
                damage: 6,
                critical: 3,
                range: "medium",
                encum: 1,
                hp: 3,
                price: 400,
                rarity: 4,
                special: "Stun setting",
                description: "Most spacers carry standard blaster pistols. They pack enough punch to penetrate plastoid armor, have decent range, and are light enough to carry around at all times. Most scoundrels also appreciate the gunslinger-style look of a well-used blaster on their hip. nSpacefarers who often have to fight aboard ship carry these weapons since the blast is effective against many types of armor, but isn't powerful enough to breach the hull of most vessels. ",
                models: "BlasTech DH-17 Blaster, BlasTech SE-14 and SE-14C Blaster Pistol",
                image: "blasterPistol"
            }
        ]);
    }

    if(loadingState !== loadingStatus.loaded) {
        console.log(loadingState);
        return <LoadingIndicator loadingState={loadingState}/>;
    }
    else
        return(

            <>
                <div className={"row mb-2"}>
                    <h5 className={"themeFontColor text-center"}>
                        Available Weapons
                    </h5>
                </div>
                <table className={"table table-hover"}>
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Skill</th>
                            <th>Dam</th>
                            <th>Crit</th>
                            <th>Range</th>
                            <th>Encum</th>
                            <th>HP</th>
                            <th>Price</th>
                            <th>Rarity</th>
                            <th>Special</th>
                        </tr>
                    </thead>
                    <tbody>
                        {weapons.map((w) => (
                            <WeaponRow key={w.id} weapon={w} />
                        ))}
                    </tbody>
                </table>
                <button className={"btn btn-primary"} onClick={addWeapon}>
                    Add
                </button>
            </>
        )
};

export default WeaponList;

I’m sure I’m missing some glaringly stupid piece here and I just can’t see it after a couple of hours messing with it.

As a quick edit here, bypassing the useWeapon hook and calling the useGetRequest hook directly in the component worked. There is either something about nesting hooks that I don’t know about or my second hook has an issue, I would think.

ReactJs img-mapper library can’t populate JSON data properly on refresh: “TypeError: Cannot read properties of undefined (reading ‘length’)”

I am using the react-img-mapper library (https://github.com/img-mapper/react-img-mapper) and it had been working fine until I needed to add functionality which requires conditional rendering of another component.

Essentially, whenever I need to set the other component’s display to true/false the page needs to refresh and the img-mapper library throws an error saying it doesn’t have the correct lengths – even tho it had been working fine on the initial load, and I’ve tried console.logging the values to see that they’re populated correctly.

Any help would be appreciated! Also open to changing my system of using JSON files if there’s any other alternative, I’m relatively new to this!

Edit: I’ve discovered that this happens on any reload of any page with an img-map, I tried pushing to the router the current page and it results in the same error.

Here is the relevant page’s code:

"use client"
import { React, useEffect, useState } from "react";
import ImageMapper from "react-img-mapper";
import { useRouter } from 'next/navigation'
import coords from "/public/JSON/coords.js";
import RecipeBook from "./RecipeBook";

export default function Kitchen() {
  const router = useRouter();
  const [showBook, setShowBook] = useState(true);
  const [kitchenCoords, setKitchenCoords] = useState(null);

  useEffect(() => {
      setKitchenCoords(coords.kitchenCoords);
  }, []); 
    
  if (!kitchenCoords) {
    return (<body className="kitchen"><h1>Loading...</h1></body>)
  }
  
  return (
    <body className="kitchen">
      <div className="tvbgContainer">
        <ImageMapper className="tvbg"
          map={{
              name:"my-map", 
              areas: kitchenCoords
              }}
          src={'/background/kitchenpage.png'}
          active={true}
          responsive={true}
          parentWidth={900}
          length={900}
          width={900}
          onClick={(e) => {
            // if it's one of the buttons, redirect there
            (e.title == "/about/me/" || e.title == "/about/credits/" || e.title == "/") ? router.push(e.title) 
            : // else show book
            // setShowBook(!showBook);
            console.log(kitchenCoords);
          }}
          />
      </div>
      {showBook && 
        <RecipeBook setShowBook={setShowBook}/>
      }
    </body>
  );
}

The JSON file, shortened with ellipses looks like this:

let kitchenCoords = [
  {
    "id": "homeButton",
    "title": "/",
    "shape": "rect",
    "fillColor": "rgba(0,0,0,0)",
    "strokeColor": "rgba(0,0,0,0)",
    "lineWidth": 2.5,
    "coords": [530,738,586,791]
  },
...
]
export default {homeCoords, kitchenCoords};

Errors

TypeError: Cannot read properties of undefined (reading 'length')

NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

Why doesn’t reactive object containing a class trigger updates?

I have a simple page with a reactive state object containing a class.

Changes to the properties in the class don’t trigger updates in the component.

A simple example component is below, but a full example can be found on vue’s playground

I’m fairly new to Vue and I’m failing to understand why classes like this don’t work so I apologise if this is a stupid question. I have spent a lot of time going through the Vue docs and StackOverflow without finding any explanation.

Is there a common pattern to do this?
I’m trying to move the data handling out of the component to reduce clutter – the full version will have lots of API calls to the server and other logic – so using a simple object in the state would be much less elegant.

If I put a simple string in the state object, update that after the repo has initialised and display that string in the template, the state.repo.items.length value will update also. This means that the array is definitely getting updated and is being referenced correctly, just that the page update is not triggering.

<script setup>
import { reactive } from 'vue';
import { Repo } from './repo';
import { onMounted } from 'vue';

  const state = reactive({
    repo: new Repo(),
    msg: 'Not Updated'
  });

  onMounted(async () => {
    await state.repo.initAsync();
  });
</script>
<template>
  <h1>Reactive Test</h1>
  <p>{{ state.repo.items.length }}</p>
</template>

check library files in typescript but don’t emit them

I’m working on an sub-module for an old school pure PHP project.
This project has a folder for some JS dependencies.

For my sanity, I’m using Typescript in the sub-module but I’m having trouble with how to reference the dependencies and get partial type inference from the libraries in the dependencies folder.

Theses dependencies are local only and I can’t change that for compatibility reasons, so I can’t really use npm.

This is the project structure :

  • Project root
    • Sub-module root
      • js
      • ts
      • tsconfig.json
    • dependencies folder

In my tsconfig.json, I have the following options :

{
    "compilerOptions": {
        // ...
        "allowJs": true,
        "checkJs": true,
        "rootDir": "./ts",
        "outDir": "./js",
        // ...
    },
    "include": [
        "./ts/**/*",
        "../dependencies/**/*.js"
    ],
}

This works pretty well. Typescript can resolve the types from the dependencies folder and correctly compiles my ./ts files into ./js. The only problem is that it keeps complaining with the following error for each file in ../dependencies :

error TS6059: File is not under 'rootDir'. 'rootDir' is expected to contain all source files.

I tried changing the ‘rootDir’ to ../. But this causes tsc to output all the dependencies into the ./js folder. I do not want that.

Display only Toolbar of kolkov/angular-editor

I want to use only the toolbar of kolkov/angular-editor but I am not able to find out how to do that currently my editor looks like this
I know there are other library as well which provides the toolbar as well but is there any way to implement it using this library

What I want is

I have an array of values which I displaying to users now I want when user right click on the cell this toolbar will get visible and through this toolbar user can make the text bold and italic

enter image description here

i just want the toolbar to look like this

this is what I want