not able to modify the current code of apigee hosted api proxy

when a making the change like just changing the numerical value and deploying the code then we are getting service unavailable, and when we are reverting back to previous commit, its working as expected. is this the APIGEE environment issue?

I am trying to push the new code changes, but my code base is not accepting the new changes, and i am expecting the new commit will work smoothly

Why is my JavaScript is returning NaN when I run the code?

I started learning programming a little while ago, but I got stuck on the functions and intervals part.

What I wanted was a very simple system, to do multiplication, using HTML and JavaScript, passing the input numbers as parameters.

However, when I run the code, it returns NaN as the result.

let button = document.querySelector("#button");
let num1 = parseInt(document.getElementById('num1').value);
let num2 = parseInt(document.getElementById('num2').value);

function operacao(a, b) {
  let resp = a * b;
  return resp;
}

let resto = operacao(num1, num2)
button.addEventListener("click", function() {
  document.getElementById('resto').innerHTML = 'O resultado é: ' + resto
});
<label>
  Informe os numeros:  
  <br>
  <input type="number" id="num1">
  <p>x</p>
  <input type="number" id="num2">
</label>
<br>
<br>
<button id="button" onclick=(operacao)>Multiplicar</button>
<p id="resto"></p>

Close a modal window with Puppeteer/NodeJS

I’m trying to close a modal window that appears when a record is invalid.
I’ve already analyzed the HTML a lot, but still can’t figure out why it isn’t closing.

I can continue the processing even if the modal remains open ; but when it does, i have a timeout on another part of my code (it waits a timeout because it doesn’t go to the next entry, just waits for the modal to be closed).

And i can’t remove this timeout, because its a timeout that i wait until an important element of the page shows up. If i leave the code without this timeout, its way prone to errors (yeah i tried all sorts of wait, this timeout was the best solution i came up).

This is the HTML code of the modal:

<div _ngcontent-cdm-c21="" style="width: 400px; max-height: 530px; min-height: 250px; margin-left: -200px; margin-top: -125px; display: block;"><h2 _ngcontent-cdm-c7="" class="title_modal title_bottom" style="padding-bottom: 1em">Erro na validação</h2><div _ngcontent-cdm-c7="" class="col-xs-12" style="border-radius: 20px; margin-left: 1px;margin-right: 1px;padding-top:1em;margin-top:-1em;padding-bottom:3em"><h2 _ngcontent-cdm-c7="" class="title_modal OpenSansLight font14">CPF Inválido</h2></div><div _ngcontent-cdm-c7="" class="col-xs-4 col-xs-offset-4" style="padding-top:0.5em"><button _ngcontent-cdm-c7="" buttontype="primary" spaui-button-custom="" class="spaui-button primary" type="submit"><!----><!----><!----><!---->OK<!----></button></div><!----><span _ngcontent-cdm-c21="" class="closeButton ng-star-inserted" id="modalCPFInvalido__dialog_close_button"><i _ngcontent-cdm-c21="" class="icon-fechar"></i></span></div>

Out of curiosity, the entire HTML code is on this link (can’t paste it here, too big because of CSS): https://pastecode.io/s/nmekts33

The method i’ve created for trying to close the modal is this one:

const handleValidationErrorModal = async (page) => {
    const errorDetected = await page.evaluate(() => {
        const errorModal = document.querySelector('h2.title_modal.title_bottom');
        if (errorModal?.textContent.includes('Erro na validação')) {
            const closeButton = document.querySelector('.closeButton .icon-fechar');
            if (closeButton) {
                closeButton.click();
                return true;
            }
        }
        return false;
    });

    if (errorDetected) {
        console.log('Validation error detected - CPF Inválido');
        await delay(100);
    }

    return errorDetected;
};

The call for the method is being made here:]

const runPuppeteer = async (filePath, login, password) => {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    let processedCount = 0;

    try {
        await handleLogin(page, login, password);
        const entries = await processXlsxFile(filePath);

        for (const group of entries) {
            for (const entry of group) {
                console.log(`Processing: ${entry.numCpfCnpj}`);
                
                await searchAndNavigate(page, entry.numCpfCnpj);
                await delay(200);

                // Handle the validation error modal if it appears
               //// const errorOccurred = await handleValidationErrorModal(page);
                //if (errorOccurred) continue;
                if (await handleCustomerSearchErrorModal(page)) continue;

I’ve also tried calling this handleErrorModal as the first method, even before the searchAndNavigate. But nothing happens also.

The page stays like this:
problem

And then i receive this error:

Error extracting table data: TimeoutError: Waiting for selector
spaui-datatable table tbody tr failed: Waiting failed: 15000ms
exceeded
at new WaitTask (C:Usersusuarionodeprojectsnode_modulespuppeteer-corelibcjspuppeteercommonWaitTask.js:50:34)
at IsolatedWorld.waitForFunction (C:Usersusuarionodeprojectsnode_modulespuppeteer-corelibcjspuppeteerapiRealm.js:25:26)
at CSSQueryHandler.waitFor (C:Usersusuarionodeprojectsnode_modulespuppeteer-corelibcjspuppeteercommonQueryHandler.js:172:95)
at async CdpFrame.waitForSelector (C:Usersusuarionodeprojectsnode_modulespuppeteer-corelibcjspuppeteerapiFrame.js:523:21)
at async CdpPage.waitForSelector (C:Usersusuarionodeprojectsnode_modulespuppeteer-corelibcjspuppeteerapiPage.js:1368:20)
at async runPuppeteer (C:UsersusuarionodeprojectspuppeteerRunner.js:173:21)
at async C:Usersusuarionodeprojectsserver.js:25:25

If i could just close the modal and retry the current numCpfCnpj, would be fine for me. But i can’t figure out the logic for doing so. I’ve just started with NodeJS after failing to accomplish this same task using C# (and it was painfully more slow also).

Out of curiosity, this is my entire puppeteer.js code:

const puppeteer = require('puppeteer');
const XLSX = require('xlsx');

// Helper function to delay execution
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// Function to handle the login process
const handleLogin = async (page, login, password) => {
    await page.goto('https://www.santandernegocios.com.br/portaldenegocios/#/externo');
    await page.waitForSelector('#userLogin__input');
    await page.type('#userLogin__input', login);
    await page.waitForSelector('#userPassword__input');
    await page.type('#userPassword__input', password);
    await page.keyboard.press('Enter');
    await page.waitForNavigation();
};

// Function to search for a CPF/CNPJ and navigate to the results
const searchAndNavigate = async (page, cpfCnpj) => {
    let retryCount = 0;
    const maxRetries = 2;

    while (retryCount <= maxRetries) {
        await page.waitForSelector('input[name="inputSearch"]');
        await page.evaluate(() => document.querySelector('input[name="inputSearch"]').value = ''); // Clear the input
        await delay(100); // Small delay before typing
        await page.type('input[name="inputSearch"]', cpfCnpj, { delay: 10 }); // Typing with a delay

        await page.waitForFunction(
            (selector, text) => document.querySelector(selector)?.value === text,
            {},
            'input[name="inputSearch"]',
            cpfCnpj
        );
        await page.keyboard.press('Enter');
        await page.waitForNavigation({ waitUntil: 'networkidle2' });

        if (!(await handleValidationErrorModal(page))) {
            break; // Exit the loop if no validation error
        }

        retryCount++;
        if (retryCount <= maxRetries) {
            console.log(`Retrying typing CPF/CNPJ (${retryCount}/${maxRetries})...`);
        } else {
            console.log('Max retries reached, proceeding to the next entry...');
        }
    }
};

// Function to process the XLSX file and group entries
const processXlsxFile = (filePath) => {
    const workbook = XLSX.readFile(filePath);
    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    const data = XLSX.utils.sheet_to_json(sheet, { header: 1 }).slice(1); // Skip header row

    return data.reduce((acc, row, index) => {
        const groupIndex = Math.floor(index / 5);
        if (!acc[groupIndex]) acc[groupIndex] = [];
        acc[groupIndex].push({
            numCpfCnpj: String(row[0]),
            numAcordo: String(row[1])
        });
        return acc;
    }, []);
};

// Function to handle the error modal if it appears
const handleValidationErrorModal = async (page) => {
    const errorDetected = await page.evaluate(() => {
        const errorModal = document.querySelector('h2.title_modal.title_bottom');
        if (errorModal?.textContent.includes('Erro na validação')) {
            const closeButton = document.querySelector('.closeButton .icon-fechar');
            if (closeButton) {
                closeButton.click();
                return true;
            }
        }
        return false;
    });

    if (errorDetected) {
        console.log('Validation error detected - CPF Inválido');
        await delay(100);
    }

    return errorDetected;
};

const handleCustomerSearchErrorModal = async (page) => {
    const errorDetected = await page.evaluate(() => {
        const errorModal = document.querySelector('h2.title_modal');
        if (errorModal?.textContent.includes('Erro na busca do cliente')) {
            document.getElementById('modalNaoCorrentistaPJ__dialog_close_button').click();
            return true;
        }
        return false;
    });

    if (errorDetected) {
        console.log('Customer search error detected');
        await delay(100);
    }

    return errorDetected;
};

// Function to click the menu link
const clickMenuLink = async (page) => {
    await page.waitForSelector('div.session-menu');
    await page.evaluate(() => {
        const sessionMenu = document.querySelector('div.session-menu ul');
        const link = Array.from(sessionMenu.querySelectorAll('li a')).find(anchor => 
            ['Acordo Pj', 'Acordo Pf'].includes(anchor.textContent.trim())
        );
        if (link) link.click();
    });
    await page.waitForNavigation();
};

// Function to click the radio button in the matching table row




// Main function to run the Puppeteer automation
const runPuppeteer = async (filePath, login, password) => {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    let processedCount = 0;

    try {
        await handleLogin(page, login, password);
        const entries = await processXlsxFile(filePath);

        for (const group of entries) {
            for (const entry of group) {
                console.log(`Processing: ${entry.numCpfCnpj}`);
                if (await handleCustomerSearchErrorModal(page)) continue;
                await searchAndNavigate(page, entry.numCpfCnpj);
                await delay(200);

                // Handle the validation error modal if it appears
               //// const errorOccurred = await handleValidationErrorModal(page);
                //if (errorOccurred) continue;
               

                await page.evaluate(() => {
                    document.querySelector('div.avatar-letters').click();
                });

                await clickMenuLink(page);
                await delay(400);
                await page.evaluate(() => {
                    const sessionMenu = document.querySelector('div.session-menu');
                    if (sessionMenu) {
                        const ul = sessionMenu.querySelector('ul');
                        if (ul) {
                            const link = Array.from(ul.querySelectorAll('li a')).find(anchor => anchor.textContent.trim() === 'Acordo Pj' || anchor.textContent.trim() === 'Acordo Pf');
                            if (link) link.click();
                        }
                    }
                });
                // Wait for the specific table to be fully loaded
               
                //await page.waitForNavigation();
                await page.evaluate(() => {
                    document.querySelector('#accordioAcordosPendentes > div.accordion-tab > div > div > h4 > span.accordion-tab-button').click();
                });
                //Going to extract data from the acordos table
                try
                {
                    await page.waitForSelector('spaui-datatable table tbody tr', { timeout: 15000 });
                    rows = await page.$$eval('spaui-datatable table tbody tr', rows => {
                        return rows.map(row => {
                            const cells = row.querySelectorAll('td');
                            
                            return {
                                product: cells[1] ? cells[1].innerText.trim() : 'N/A',
                                contractDate: cells[2] ? cells[2].innerText.trim() : 'N/A',
                                contractNumber: cells[3] ? cells[3].innerText.trim() : 'N/A',
                                contractedValue: cells[4] ? cells[4].innerText.trim() : 'N/A',
                                dueDate: cells[5] ? cells[5].innerText.trim() : 'N/A',
                                status: cells[6] ? cells[6].innerText.trim() : 'N/A',
                            };
                        });
                    });
                    console.log(rows);
                }
                catch(error)
                {
                    console.error('Error extracting table data:', error);
                    rows = []; // Ensure rows is an array even if empty
                }
                // Find the row where the contractNumber equals numAcordo and try to click the radio button
                const matchingRowIndex = rows.findIndex(row => row.contractNumber === entry.numAcordo);
                if (matchingRowIndex !== -1)
                {
                    console.log(matchingRowIndex)
                }
                
                
                console.log(`Processed: ${entry.numCpfCnpj} - ${entry.numAcordo}`);
                processedCount++;
            }
        }
    } catch (error) {
        console.error('Error occurred:', error);
    } finally {
        console.log(`Total processed entries: ${processedCount}`);
        await browser.close();
    }
};

module.exports = { runPuppeteer };

Thanks in advance for any input, and sorry for the long posting.
BTW: Should i try to make these questions smaller, or provide the maximum details as possible?

Setting two classes to the same width/max-width using Javascript

I’m trying to dynamically set two divs to the same max-width using javascript.. I have this so far:

window.onload = function setWidth() {
  var one = document.getElementsByClassName("adsm-skin site-main");
  var two = document.getElementsByClassName("pn-print-page");
    style = window.getComputedStyle(one);
    wdt = style.getPropertyValue("max-width");
    two.style.maxWidth = wdt;
}

However it’s not working (the .pn-print-page isn’t registering having any max-width at all on page load when I’d like it to match .adsm-skin .site-main)

I’ve also tried this:

window.onload = function () {
function setWidth() {
  var one = document.querySelector(".other-div");
  var two = document.querySelector(".pn-print-page");
  style = window.getComputedStyle(one);
  wdt = style.getPropertyValue('width');
  two.style.width = wdt;
}
};

No width is being added to pn-print-page either.. Is there something wrong with the code? If not do you know any other ways of doing this using javascript..? Thanks in advance

Video is not playing when passing video source as a blob url on android edge

I am using html5 video player for playing video. I have the video hosted as a public video. I am downloading the video and then converting it into a blob and then using createObjectURL() method to get a blob url but it is not playing the video on android edge only. No error or warning in the console.

https://jsfiddle.net/h12kmvdq/

fetch(
    "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerMeltdowns.mp4" 
)
.then((videoResponse) => {
  videoResponse.blob().then((blobData) => {
    blobData.arrayBuffer().then((blobArray) => {
      const videoBlob = new Blob([blobArray], { type: "video/mp4" });
      const videoSrc = URL.createObjectURL(videoBlob);
      console.log(videoSrc, 'video src');
      const videoElement = document.getElementById('video');
      videoElement.src = videoSrc;
      setTimeout(() => {
        videoElement.play();
      }, 200);
    });
   })
})l

React – dropdown component not displaying

I’m following a tutorial on youtube for creating a Navbar since I have no experience with Rect and JavaScript.I’m having a problem displaying a dropdown when hovering over a specific list item in my navbar (in the yt tutorial it works just fine) and I can’t figure out how to fix it.

import React, { useState } from 'react';
import { Button } from './Button';
import { Link } from 'react-router-dom';
import Dropdown from './Dropdown';
import './styles/nav-bar.css';

function NavBar() {

  const [click, setClick] = useState(false);
  const [dropdown, setDropdown] = useState(false);

  const handleClick = () => setClick(!click);

  const closeMobileMenu = () => setClick(false);

  const onMouseEnter = () => {
    if (window.innerWidth >= 960) {
      console.log("Testing onMouseEnter - Hovering over Tournaments list item") // test = OK
      setDropdown(true);
    }
  }
  const onMouseLeave = () => {
    setDropdown(false);
  };
    
  return(
    <>
      <nav className='navbar'>
        <Link to='/' className='navbar-logo'>
          <h2>KICKOFF</h2>
        </Link>
      
        <div className='menu-icon' onClick={handleClick}>
          <i className={click ? 'fas fa-times' : 'fas fa-bars'}></i>
        </div>

        <ul className={click ? 'nav-menu active' : 'nav-menu'}>
          <li className="nav-item">
            <Link to='/' className='nav-links' onClick={closeMobileMenu}>
              Home
            </Link>
          </li>
          <li className="nav-item">
            <Link to='/players' className='nav-links' onClick={closeMobileMenu}>
              Players
            </Link>
          </li>
          <li className="nav-item" onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>
            <Link className='nav-links' onClick={closeMobileMenu}>
              Tournament <i className='fas fa-caret-down' />
            </Link>
            {dropdown && <Dropdown />}
          </li>
          <li className="nav-item">
            <Link className='nav-links' onClick={closeMobileMenu}>
              Contact Us
            </Link>
          </li>
        </ul>
        <Button />
      </nav>
    </>
  );
}
export default NavBar;

Looks like the logic behind onMouseEnter function is to change dropdown to true so that this part of the code {dropdown && <Dropdown />} displays, but nothing happens.
Function onMouseEnter is working since I can see the message in ma console, but looks like the value is not changing right?
If it was changed it would display the Dropdown component.

This is the Dropdown component

import React, { useState } from 'react';
import { MenuItems } from './MenuItems';
import { Link } from 'react-router-dom';
import './styles/dropdown.css';

function Dropdown() {

  const [click, setClick] = useState(false);

  const handleClick = () => setClick(!click);

  return(
    <>
      <ul onClick={handleClick}
        className={click ? 'dropdown-menu clicked' : 'dropdown-menu'}>
          {MenuItems.map((item, index) => {
            return(
              <li key={index}>
                <Link className={item.cName} to={item.path} onClick={() => { setClick(false) }} >
                  {item.title}
                </Link>
              </li>
            )
          })}
      </ul>
    </>
  );
}

export default Dropdown;

dropdown.css

.dropdown-menu {
  width: 200px;
  position: absolute;
  top: 80px;
  list-style: none;
  text-align: start;
}
.dropdown-menu li {
  background: #292828;
  cursor: pointer;
}
.dropdown-menu li:hover {
  background: #424242;
}
.dropdown-menu.clicked {
  display: none;
}
.dropdown-link {
  display: block;
  width: 100%;
  height: 100%;
  text-decoration: none;
  color: #fff;
  padding: 16px;
}

moment startOf(‘year’) & endOf(‘year’) gives different ISO date string

I am struggling to understand why moment startOf('year') and endOf('year') result in a different ISO string in local machine and on cloud. I am assuming its a timezone issue but ISO string looks like its in UTC, so it should return same ISO string. I’d like to understand if its a timezone issue how should I ensure that different timezone does not affect my code.

In local it returns start of year as '2022-12-31T19:00:00.000Z' and in cloud it gives 2023-01-01T00:00:00.000Z

So my code is

// find current year start and end
const startOfYear = moment(currentDate).startOf('year').toDate();
const endOfYear = moment(currentDate).endOf('year').toDate();

return {
  start: startOfYear,
  end: endOfYear,
};

The unit test I wrote which PASS in local but FAIL in cloud in case you are interested in what I am doing

const timestamp = new Date('2023-05-15T00:00:00Z');
const expectedStart = new Date('2022-12-31T19:00:00.000Z');
const expectedEnd = new Date('2023-12-31T18:59:59.999Z');

const result = getFinancialYearDates(timestamp);

expect(result.start).toStrictEqual(expectedStart);
expect(result.end).toStrictEqual(expectedEnd);

Wait for an element to exist

im trying the below code but im getting undifined “length” cuz the element in the select is not yet created that cuz im using a plugin and this element is inside this plugin template and the plugin take a litte more time to load after the DOM loads.what can i do to wait for the element to load?

what i want to do

var select = document.getElementsByClassName("pp_pricing_options")[0];
var plan = localStorage.getItem("Plan");
plan = plan.replaceAll(/s+/g, '');
plan = plan.toLowerCase();
plan = plan.charAt(0).toLocaleUpperCase() + plan.substring(1);
for(var i = 0; i < select.length; i++)
{
    if(select[i].text.includes(plan)){
        select[i].selected = true;
    }
}

what i have tried

document.addEventListener("DOMContentLoaded", () => {
    var select = document.getElementsByClassName("pp_pricing_options")[0];
    var plan = localStorage.getItem("Plan");
    plan = plan.replaceAll(/s+/g, '');
    plan = plan.toLowerCase();
    plan = plan.charAt(0).toLocaleUpperCase() + plan.substring(1);
    for(var i = 0; i < select.length; i++)
    {
      if(select[i].text.includes(plan)){
         select[i].selected = true;
      }
    }
});
window.onload = function(){
     var select = document.getElementsByClassName("pp_pricing_options")[0];
     var plan = localStorage.getItem("Plan");
     plan = plan.replaceAll(/s+/g, '');
     plan = plan.toLowerCase();
     plan = plan.charAt(0).toLocaleUpperCase() + plan.substring(1);
     for(var i = 0; i < select.length; i++)
     {
      if(select[i].text.includes(plan)){
          select[i].selected = true;
      }
     }
}

i have also tried the document ready function using jquery

i also tried the solutions in this link but my await keeps waiting with no response
How to wait until an element exists?

the code i typed

$(document).ready(function () {
        async function waitForElm(selector) {
            return new Promise(resolve => {
                    if (document.querySelector(selector)) {
                            return resolve(document.querySelector(selector));
                    }

                    const observer = new MutationObserver(mutations => {
                            if (document.querySelector(selector)) {
                                    observer.disconnect();
                                    resolve(document.querySelector(selector));
                            }
                    });

                    // If you get "parameter 1 is not of type 'Node'" error, see https://stackoverflow.com/a/77855838/492336
                    observer.observe(document.body, {
                            childList: true,
                            subtree: true
                    });
            });
    }

    async function start(){
        var select = await waitForElm("pp_pricing_options");
        var plan = localStorage.getItem("Plan");
        plan = plan.replaceAll(/s+/g, '');
        plan = plan.toLowerCase();
        plan = plan.charAt(0).toLocaleUpperCase() + plan.substring(1);
        for(var i = 0; i < select.length; i++)
        {
            if(select[i].text.includes(plan)){
                select[i].selected = true;
            }
        }
    } 
    start();
});

i belive the last one is the right solution but i cant get it to work for some reason. but please if you have better/easier solutions tell me.

Postmessage of array in then promise.all method doesn’t send

I have some javascript code that functions as part of an application to update elements in the DOM of a webpage. For performance, I spawn a worker that accesses a rest endpoint to get some data, then uses that data to make another call to another endpoint to get other data based on that data. The intent is to return this data back to the main script so that it then will update the DOM with this data.

During this process I declare a global array projectsDataJSON in the worker which holds the result that I want to send back to the parent script, and this array is being populated by the functions of the worker script with the correct data.

However when I try to send the object using post message I get an empty array. The values actually disappear, so I am unable to transfer my result to the parent script successfully.

Here is my source code for the parent script:

    console.log("Spawning a Worker to retrieve the Projects")
    var worker = new Worker('/SiteAssets/AssetDigitalAssets/getAllAssociatedProjectsWorker.js');
    
    worker.addEventListener('message', function(e) {
        responseObject = e.data;
        console.log ("what follows is the response we got from the worker")
        console.log(e);
        console.log ("what follows is what we set to the responseObject")
        console.log (responseObject)
        if (responseObject.length != 0) {
            if (responseObject.d.results.length > 0) {
                console.log(responseObject.d.results) 
                updateProjectsDT(responseObject.d.results)
            }   
        }
        else {
            console.log("No Associated Projects Returned from worker action")
        }
        
    }, false);
    
    worker.postMessage(selectedDigitalAssetRecordID);

Here is the source code for the worker getAllAssociatedProjectWorker.js

var projectsDataJSON = [];
var editProjectHTML = "<span class="ms-cui-ctl-iconContainer" unselectable="on"><span class="ms-cui-img-16by16 ms-cui-img-cont-float ms-cui-imageDisabled" unselectable="on" ><img alt="" id="documentEditImage" style="top: -128px;left: -224px;" unselectable="on" src="/_layouts/1033/images/formatmap16x16.png" /></span></span>";
var delProjectAssociationHTML = "<span class="ms-cui-ctl-iconContainer" unselectable="on"><span class="ms-cui-img-16by16 ms-cui-img-cont-float ms-cui-imageDisabled" unselectable="on"><img class="" style="top: -48px;left: -96px;" unselectable="on" src="/_layouts/1033/images/formatmap16x16.png"></span></span>";

self.addEventListener('message', function(e) {
    getAllAssociatedProjectsWithPromises(e.data);
}, false);


//this is an attempt to get the second set of records from projects
//using promises.all  
function getAllAssociatedProjectsWithPromises(DARID) {
    console.log ("running getAllAssociatedProjectsWithPromises...")
    var xmlHttpProjectAssetDocuments = new XMLHttpRequest();

    xmlHttpProjectAssetDocuments.onreadystatechange = async () => {
        if(xmlHttpProjectAssetDocuments.readyState == XMLHttpRequest.DONE){
            if(xmlHttpProjectAssetDocuments.status == 200){
                console.log("Response was 200...")
                const ProjectAssetDocumentsResponseObject = JSON.parse(xmlHttpProjectAssetDocuments.responseText)
                console.log("ProjectAssetDocumentsResponseObject follows")
                console.log(ProjectAssetDocumentsResponseObject)
                console.log("ProjectAssetDocumentsResponseObject.d.results.length follows")
                console.log(ProjectAssetDocumentsResponseObject.d.results.length)
                
                if (ProjectAssetDocumentsResponseObject.d.results.length > 0) {
                    projectCount = ProjectAssetDocumentsResponseObject.d.results.length
                    console.log("We Found " & projectCount & " projects.")

                    const res = await Promise.all(ProjectAssetDocumentsResponseObject.d.results.map(d => getProject(d.Id,d.ProjectID)))
                    //this actually shows the correct data that I want to transfer to the main Javascript code
                    console.log('All the Promises were resolved what follows is the projectsDataJSON')
                    console.log(projectsDataJSON);
                    //this however does not work, the log in the main javascript code recieves an empty message.
                    var myResponse
                    myResponse = JSON.stringify(projectsDataJSON)
                    console.log ("what myResponse is set to")
                    console.log (myResponse)
                    postMessage(myResponse)
                } else {
                    console.log("We found 0 associated projects.")
                }
                
            } else if (xmlHttpProjectAssetDocuments.status == 400){
                console.log("not found")
            } else {
                console.log("other")
            }
        }
    }

    //this triggers the call to the server.
    xmlHttpProjectAssetDocuments.open("GET","https://{OurServer}/_vti_bin/listdata.svc/ProjectAssetDocuments?$select=Id,ProjectID,AssetDocumentsID&$filter=AssetDocumentsID eq " + DARID,true);
    xmlHttpProjectAssetDocuments.setRequestHeader("Accept", "application/json; odata=verbose")
    xmlHttpProjectAssetDocuments.send()

    
}



function getProject(projectAssetDocumentsID, projectId) {
    var xmlHttpProjects = new XMLHttpRequest(); 
    var currentProjectID
    var currentProjectSMMID
    var currentProjectTitle

    //get a project record and add it to the projectDataJSON []
    xmlHttpProjects.onreadystatechange = function (){
        //for some reason, this logs three times per run.  No clue why.
        console.log("we are getting project id " + projectId)
        if(xmlHttpProjects.readyState == XMLHttpRequest.DONE ) {
            if(xmlHttpProjects.status == 200) {
                var projectsResponseObject = JSON.parse(xmlHttpProjects.responseText)
                console.log ("response for projectid " + projectId + " follows")
                console.log (projectsResponseObject)
                currentProjectID = projectsResponseObject.d.results[0].Id
                currentProjectSMMID = projectsResponseObject.d.results[0].SMM000000
                currentProjectTitle = projectsResponseObject.d.results[0].ProjectNameTitleDescription

                var obj = {
                    'ID': projectAssetDocumentsID,
                    'CurrentProjectID': currentProjectID,
                    'Edit' : editProjectHTML,
                    'SMMID': currentProjectSMMID,
                    'Title': currentProjectTitle,
                    'Delete': delProjectAssociationHTML,
                }
                
                projectsDataJSON.push(obj);
            } else if (xmlHttpProjects.status == 400){
            console.log("getProject not found")
            } else {
                console.log("other error in getProject")
            }
        }

    }

    //this triggers the call to the server.
    xmlHttpProjects.open("GET","https://{OurServer}/_vti_bin/listdata.svc/Projects?$select=Id,SMM000000,ProjectNameTitleDescription&$filter=Id eq " + projectId,true);
    xmlHttpProjects.setRequestHeader("Accept", "application/json; odata=verbose")
    xmlHttpProjects.send()
}

Here is the output from the console log with my annotations

Console Log Screenshot

bug when redirect user when token expired in react js

i need help, i try to redirect user when user are not authenticate specifically, when token is expired.
but when user redirected to login page, if user want login again. they have to click handlesubmit login twice to login.

how when user only just click once to login

here’s the code:

login code:

import LoginPageView from "./view";
import * as Yup from "yup";
import { useLoginMutation } from "../../store/service";
import { toast } from "react-toastify";
import { useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
import { setItem } from "../../utils";

const LoginPage = () => {
  const [login, result] = useLoginMutation();
  const [showPassword, setShowPassword] = useState(false);
  const navigate = useNavigate();

  const loginSchema = Yup.object().shape({
    email: Yup.string().email("Invalid email").required("Email Required"),
    password: Yup.string().required("Password Required"),
  });

  const initialValues = {
    email: "",
    password: "",
  };

  async function handleSubmit(values) {
    try {
      await login(values).unwrap();
      toast.success("Login Successfully");
    } catch (error) {
      result.reset();
      toast.error(error.data?.message || "Login failed");
    }
  }

  function handleToggleShowPassword() {
    setShowPassword((prev) => !prev);
  }



  useEffect(() => {
    if (result?.isSuccess) {
      const { role, token } = result?.data?.data || {};

      // set to local storage
      setItem("token", token);

      if (role === "user") {
        navigate("/explore");
      } else if (role === "admin") {
        navigate("/dashboard");
      }
    }
  }, [result?.isSuccess, navigate]);

  useEffect(() => {
    if (result?.isError) {
      console.log(result.error);
    }
  }, [result?.isError]);

  useEffect(() => {
    return () => {
      result.reset();
    };
  }, []);

  return (
    <LoginPageView
      initialValues={initialValues}
      validationOnLogin={loginSchema}
      onSubmit={handleSubmit}
      onShowPassword={handleToggleShowPassword}
      showPassword={showPassword}
    />
  );
};

export default LoginPage;

Route protected component code:

import { Navigate, Outlet } from "react-router-dom";
import { useGetCurrentUserApiQuery } from "../../store/service";
import { removeItem } from "../../utils";

export function ProtectedRoute({ statusRole }) {
  const { data, isError, error } = useGetCurrentUserApiQuery();


  if (isError && error?.status === 401) {
    removeItem("token")
    return <Navigate to={"/"} />;
  }

  if (data && data?.data?.role === statusRole) {
    return <Outlet />;
  } 

}

How can I add purecounter.js to my WordPress site?

<div class="counter-number">
  <span data-purecounter-start="0"
        data-purecounter-end="6"
        data-purecounter-duration="1"
        class="purecounter"></span>
</div>
new PureCounter();
wp_register_script(
  'purecounter',
  get_template_directory_uri() . '/assets/vendor/purecounter/purecounter_vanilla.js',
  array('jquery'),
  '1.5.0',
  true
);
wp_enqueue_script('purecounter');
Uncaught ReferenceError: PureCounter is not defined

The counter number not showing. Getting this error.

Error. React Native Expo. The program gives the error: “eferenceError: Property ‘list’ doesn’t exist, js engine: hermes”

The program gives the error: “eferenceError: Property ‘list’ doesn’t exist, js engine: hermes”. I believe this is due to incorrectly passing addItem or using useState. Tell me, how can I fix the code so that everything works?

App.js:

export default function App() {
  
  const [listOfItems, setListOfItems] = useState([
    {text:"TEST", fav: true, key: Math.random().toString(36).substring(7)},
    {text:"TEST2n1n2n3", fav: false, key: Math.random().toString(36).substring(7)} 
  ]);  // {text:"", fav:t|f, key: Math.random().toString(36).substring(7)} 

  const addItem = (data) => {
    setListOfItems((list) => [
      // { text: data.text, fav: data.fav, key: Math.random().toString(36).substring(7) },
      { text: data.text, fav: data.fav, key: Math.random().toString(36).substring(7) },
      ...list,
    ]);
  };

  const deleteItem = (key) => {
    setListOfItems((list) => list.filter(item => item.key !== key));
  };

  const changeItem = (key, data) => {
    setListOfItems((list) => {
      const itemIndex = list.findIndex(item => item.key === key);
      if (itemIndex !== -1) {
        const updatedList = [...list];
        updatedList[itemIndex] = { ...updatedList[itemIndex], ...data };
        return updatedList;
      }
      return list;
    });
  };

  const Tab = createBottomTabNavigator();
  return (
      <NavigationContainer>
          <Tab.Navigator>
            <Tab.Screen name="Favorites" component={Favorites} initialParams={{listOfItems}} />
            <Tab.Screen name="Home" component={MainList} initialParams={{listOfItems}}/>
            <Tab.Screen name="Create" component={Form} initialParams={{addItem}}/>
            <Tab.Screen name="Settings" component={Settings} />
        </Tab.Navigator>
      </NavigationContainer>
  );
};

FormCreate.js:

export default function Form({ route }) {
    const [data, setValue] = useState({ text: "", fav: false });
    const { addItem } = route.params;

    const onChangeText = (item) => {
        setValue(prevState => ({ ...prevState, text: item }));
    };

    const onChangeFavorite = () => {
        setValue(prevState => ({ ...prevState, fav: !prevState.fav }));
    };

    return (
        <View>
            <Pressable style={styles.but} onPress={onChangeFavorite}>
                <Text style={{ color: 'white' }}>Favorite</Text>
            </Pressable>
            <TextInput 
                style={styles.input} 
                onChangeText={onChangeText} 
                placeholder='Enter task content...' 
            />
            <Pressable onPress={() => addItem(data)} style={styles.but}>
                <Text style={{ fontWeight: 'bold', color: 'white', textAlign: 'center' }}>Add</Text>
            </Pressable>
        </View>
    );
}

This is the module where the addItem function is passed, everything goes well until the setListOfItems function is called in App.js

Svelte and springboot Resumable Upload

I need guidance. I’ve been looking for a third party library that I can use, to manage the Resumable (resumablejs) upload of a very large file (>5GB). It’s important that it be resumable. Please help or point me in the right direction. I’m using Svelte for the front end. Thanks in advance

shadcn card – semantic HTML

when using card.tsx from shadcn I see that’s a div styled with tailwind (the card itself). Should I change it to section instead of div for semantic HTML? should I change also the footer (adding footer for example), header (adding header tag) for semantic HTML ?

const Card = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
  ({ className, ...props }, ref) => (
    <div
      ref={ref}
      className={cn(
        "rounded-xl border bg-card text-card-foreground shadow-md",
        className,
      )}
      {...props}
    />
  ),
);

const CardHeader = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
  ({ className, ...props }, ref) => (
    <div
      ref={ref}
      className={cn("flex flex-col space-y-1.5 p-6", className)}
      {...props}
    />
  ),
);

const CardTitle = forwardRef<
  HTMLParagraphElement,
  HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
  <h3
    ref={ref}
    className={cn("font-semibold leading-none tracking-tight", className)}
    {...props}
  />
));

const CardDescription = forwardRef<
  HTMLParagraphElement,
  HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
  <p
    ref={ref}
    className={cn("text-sm text-muted-foreground", className)}
    {...props}
  />
));

const CardContent = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
  ({ className, ...props }, ref) => (
    <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
  ),
);
CardContent.displayName = "CardContent";

const CardFooter = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
  ({ className, ...props }, ref) => (
    <div
      ref={ref}
      className={cn("flex items-center p-6 pt-0", className)}
      {...props}
    />
  ),
);
CardFooter.displayName = "CardFooter";