Fixing ‘reducer’ Required Argument Error in Redux Saga

I am trying to learn redux saga by following the below tutorial.
but when I include the below line I am getting an error.

Error in /turbo_modules/@reduxjs/[email protected]/dist/redux-toolkit.cjs.development.js (525:15)
“reducer” is a required argument, and must be a function or an object of functions that can be passed to combineReducers

can you let me know how to fix it
providing my code below
I installed all the packages and tried to debug but still no luck.
I have created actions and reducers too

https://stackblitz.com/edit/react-9czykt?file=index.tsx,pages%2FHome.tsx,pages%2FAbout.tsx,App.tsx,reducers%2Freducers.js,actions%2Factions.js,API.tsx

https://ibjects.medium.com/getting-started-with-redux-saga-tutorial-740954fc9e49

import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
import { StyledEngineProvider } from '@mui/material/styles';
import Demo from './Demo';
import Home from './pages/Home';
import About from './pages/About';
import Products from './pages/Products';
import Error from './pages/Error';
import SharedLayout from './pages/SharedLayout';
import SingleProduct from './pages/SingleProduct';
import Dashboard from './pages/Dashboard';
import Login from './pages/Login';
import { Provider } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';
//import { myReducer } from '../reducers';
import createSagaMiddleware from '@redux-saga/core';
import { myReducer } from './reducers/reducers';

import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { useState } from 'react';

import { createRoot } from 'react-dom/client';
const sagaMiddleware = createSagaMiddleware();
//const store = configureStore({ reducer: myReducer });

// const store = configureStore({
//   reducer: myReducer,
//   middleware: [sagaMiddleware],
// });

const App = () => {
  const [user, setUser] = useState(null);

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<SharedLayout />}>
          <Route index element={<Home />} />
          <Route path="about" element={<About />} />
          <Route path="products" element={<Products />} />
          <Route path="products/:productId" element={<SingleProduct />} />
          <Route path="login" element={<Login setUser={setUser} />} />
          <Route path="login" element={<Login setUser={setUser} />} />

          <Route path="*" element={<Error />} />
        </Route>
      </Routes>
      <StyledEngineProvider injectFirst>
        <Demo />
      </StyledEngineProvider>
    </BrowserRouter>
  );
};

createRoot(document.querySelector('#root')!).render(
  <React.StrictMode>
    {/* <Provider store={store}> */}
    <App />
    {/* </Provider> */}
  </React.StrictMode>
);

Add persistent global function across pages via window, or localstorage, etc

I am trying to hide an icon on a page I can’t edit directly. I need to add a function that has in it document.getElementById('icon').style.display = 'none';. I don’t need help with the function.

So more in-depth: there is a page, let’s call it unEditPage, that I cannot edit directly. It doesn’t share any resources like our other pages on the website do – aka no global js files or css.

unEditPage and all other pages that I have access to are all on the same domain.

I’ve tried attaching an event listen to the window and fire on url contains, but that listener is destroyed on page navigation.

Solution would be something I can inject in another page that carries over to the unEditable page. Something maybe using unload, localstorage, cookies, or global something.

Slow Web Scrapping

i have this code to scrap a website, but in my computer it runs really slow, can someone with some more experiencia can tell me what am i doing wrong? I´m using puppeteer in js, this is a page of real state in mexico, so probably you’ll need to understand a little bit of spanish, I tried to use the network in the inspector but i don´t find any call to an api that is usefull for the info i need

const mysql = require('mysql2');
const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth');

puppeteer.use(StealthPlugin());

function delay(time) {
    return new Promise(function(resolve) { 
        setTimeout(resolve, time)
    });
}

async function createInmueble(page, info){

    return await page.evaluate((info) => {
        let inmueble = {};

        inmueble.titulo = info.title;
        inmueble.precios = info?.priceOperationTypes?.[0]?.prices?.[0]?.amount.toString() || document.querySelector(".price-items").firstElementChild.textContent.trim().split(" ")[1];
        inmueble.moneda = info?.priceOperationTypes?.[0]?.prices?.[0]?.isoCode || document.querySelector(".price-items").firstElementChild.textContent.trim().split(" ")[0];
        inmueble.inmobiliaria = info?.publisher?.name || null;
        inmueble.tipo = info?.realEstateType?.name || null;
        inmueble.estado = info?.postingLocation?.location?.parent?.parent?.name || null;
        inmueble.municipio = info?.postingLocation?.location?.parent?.name || null;
        inmueble.zona = info?.postingLocation?.location?.name || null;
        inmueble.latitud = info?.postingLocation?.postingGeolocation?.geolocation?.latitude.toString() || null
        inmueble.longitud = info?.postingLocation?.postingGeolocation?.geolocation?.longitude.toString() || null
        inmueble.imagenes = info?.pictures?.map(picture => picture.url1200x1200) || null;
        inmueble.metros_totales = info?.mainFeatures?.CFT100?.value || "0";
        inmueble.metros_construidos = info?.mainFeatures?.CFT101?.value || "0";
        inmueble.banios = info?.mainFeatures?.CFT3?.value || "0";
        inmueble.estacionamientos = info?.mainFeatures?.CFT7?.value || "0";
        inmueble.recamaras = info?.mainFeatures?.CFT2?.value || "0";
        inmueble.antiguedad = info?.mainFeatures?.CFT5?.value || "0";
        inmueble.medio_banio = info?.mainFeatures?.CFT4?.value || "0";
        inmueble.direcciones = info?.postingLocation?.address?.name || null;
        inmueble.new_latitud = inmueble?.latitud || null;
        inmueble.new_longitud = inmueble?.longitud || null;
        inmueble.url = info?.seoAttributes?.canonical || null;
        inmueble.telefono = info?.whatsApp;
        inmueble.nombre_asesor = null;
        inmueble.email = null;

        return inmueble;
    }, info);
}

async function getInfoInmueble(page){
    console.log(page.url());

    const info = await page.evaluate(() => {

        return POSTING;
    });

    return info;
}

async function scopeEnlaces(page, enlaces){
    let info;
    let inmuebles = [];
    for(const enlace of enlaces){
        try{
            await page.goto(enlace);
            info = await getInfoInmueble(page);
            const inmueble = await createInmueble(page, info);
            inmuebles.push(inmueble);
        }
        catch(err){
            console.error("error", enlace);
        }
    }

    return inmuebles;
}

async function getEnlaces(page){
    const enlaces = await page.evaluate(() => {

        try{
            let div_padre = document.querySelector(".postings-container");

            const div_hijo = Array.from(div_padre.children);

            const enlaces = div_hijo.map(div => {
                const link_base = "https://www.vivanuncios.com.mx";
                const div_enlace = div.firstElementChild;
                const enlace = div_enlace.getAttribute("data-to-posting");

                return link_base+enlace;
            }).filter(enlace => enlace !== null);

            return enlaces;
        }
        catch(err){
            console.log("Error en page:", err);
            return [];
        }
    });

    return enlaces;
}

async function getInmuebles(page, url) {
    await page.goto(url);
    const enlaces = await getEnlaces(page);
    return await scopeEnlaces(page, enlaces);
}

async function postInmueble(inmueble){
    let query = `INSERT INTO inmueblesvivanuncio (titulo, precios, moneda, inmobiliaria, tipo, estado, municipio, zona, latitud, longitud, imagenes, metros_totales, metros_construidos, banios, estacionamientos, recamaras, antiguedad, medio_banio, direcciones, new_latitud, new_longitud, url, telefono, nombre_asesor, email) VALUES ('${inmueble.titulo}', '${inmueble.precios}', '${inmueble.moneda}', '${inmueble.inmobiliaria}', '${inmueble.tipo}', '${inmueble.estado}', '${inmueble.municipio}', '${inmueble.zona}', '${inmueble.latitud}', '${inmueble.longitud}', '${JSON.stringify(inmueble.imagenes)}', '${inmueble.metros_totales}', '${inmueble.metros_construidos}', '${inmueble.banios}', '${inmueble.estacionamientos}', '${inmueble.recamaras}', '${inmueble.antiguedad}', '${inmueble.medio_banio}', '${inmueble.direcciones}', '${inmueble.new_latitud}', '${inmueble.new_longitud}', '${inmueble.url}', '${inmueble.telefono}', '${inmueble.nombre_asesor}', '${inmueble.email}')`;
    
    connection.query(query, (error, results, fields) => {
        if (error){
            console.log("error", error);
        }
        else{
            console.log('Fila insertada con éxito');
        }
    });
}

async function scopeInmuebles(all_inmuebles){
    await all_inmuebles.forEach(async inmueble => {
        try{
            await postInmueble(inmueble);
        }
        catch(err){
            console.error("surgio un error");
        }
    });
}

async function getBotonSiguiente(page){
    const boton = await page.evaluate(() => {
        const boton = document.querySelector(".sc-n5babu-2.kNwjYM");

        if(boton){
            return true;
        }

        return false;
    });

    return boton
}

async function scanPage(page){
    const BASE_URL = 'https://www.vivanuncios.com.mx/s-casas-en-venta';
    let estado = "chihuahua";
    let i = 16;
    let all_inmuebles = [];
    let boton;

    do{
        let url = `${BASE_URL}/${estado}/page-${i}`;
        console.log("Pagina nueva: ", url, "n");

        const inmuebles = await getInmuebles(page, url);
        all_inmuebles = all_inmuebles.concat(inmuebles);

        await page.goto(url);
        
        if(i%5 == 0){ 
            await scopeInmuebles(all_inmuebles);
            all_inmuebles = [];
        }

        boton = await getBotonSiguiente(page);
        if (boton) {
            i++;
        } else {
            console.log("No hay boton");
            await scopeInmuebles(all_inmuebles);
        }

    } while(boton && i <= 1000);

    return all_inmuebles;
}

async function scrapeo(){
    const browser = await puppeteer.launch({headless: false, executablePath: "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"});
    const page = await browser.newPage();
    
    const inmuebles = await scanPage(page);

    await browser.close();

    return inmuebles;
}

async function main(){
    const all_inmuebles = await scrapeo();
    connection.end();
}

const connection = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: 'CocacolA&_2016',
    database: 'InmobiliariaPrueba'
});

connection.connect();

main();

I have try concurrency but it just makes it slower

Do you know why the error message “TypeError: expressJwt is not a function” is appearing? How can it be fixed?

const expressJwt = require('express-jwt')

function authJwt() {
    const secret = process.env.secret
    return expressJwt({
        secret,
        algorithms: ['HS256']
    })
}

module.exports = authJwt
C:code-wldnfinal-projectwldn-apihelpersjwt.js:5
return expressJwt({
       ^

TypeError: expressJwt is not a function
    at authJwt (C:code-wldnfinal-projectwldn-apihelpersjwt.js:5:12)
    at Object.<anonymous> (C:code-wldnfinal-projectwldn-apiapp.js:18:9)

enter image description here

ASAP… I tried to resolve the error message “TypeError: expressJwt is not a function” by ensuring that express-jwt is properly imported and used as a function in the jwt.js file. I expected the error to be resolved, allowing the application to run without any issues related to expressJwt. However, the error persisted despite my attempts to address it.

delete button y addButton

I built a website where you can save and delete times. At the beginning I can save. But when I delete, I delete all times and can no longer save anything. Also, when I reload the page, what I deleted is back. Can anybody help me with this? Thanks in advance!

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Arbeitszeiten App</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            gap: 16px;
            background-color: white;
            font-family: "Roboto";
        }

         #addbutton {
            background-color: rgb(7, 158, 240);
            color: white;
            border: none;
            font-size: 20px;
            padding: 16px;
            cursor: pointer;
        }

        #deletebutton{
            background-color: red;
            color: white;
            border: none;
            font-size: 20px;
            padding: 16px;
            cursor: pointer;
        }


        input {
            border: 1px solid rgba(0, 0, 0, 0.12);
            height: 50px;
            border-radius: 8px;
            width: calc(100% - 16px);
        }

        .list-item {
            background-color: white;
            border: 1px solid rgba(0, 0, 0, 0.12);
            padding: 16px;
            border-radius: 8px;
            font-weight: 60;
            display: flex;
            align-items: center;
            gap: 16px;
            margin-bottom: 16px;
        }

        .small-img {
            width: 24px;
            height: 24px;
        }
    </style>
</head>

<body>


    <h1>Arbeitszeiten</h1>
    <input id="myDate" placeholder="Datum einfügen" type="date">
    <input id="myStartTime" placeholder="Startzeit einfügen" type="time">
    <input id="myEndTime" placeholder="Endzeit einfügen" type="time">
    <button id="addbutton" onclick="addWorktime()">Speichern</button>
    <button id="deletebutton" onclick="deleteWorktime()" onclick="sicherheitsabfrage()"> Alle Arbeitszeiten löschen</button>


    <div id="myWorkingHours">

    </div>

    <script src="script.js"></script>

</body>

</html>

and the javascript file:



function deleteWorktime() {
    let myWorkingHours = document.getElementById("myWorkingHours");
    myWorkingHours.parentNode.removeChild(myWorkingHours)
}

function sicherheitsabfrage(){
    confirm(message)
}

myWorkingHours.innerHTML = localStorage.getItem('html');

function addWorktime() {

    let currentDate = myDate.value;
    let startTime = myStartTime.value;
    let endTime = myEndTime.value;

    myWorkingHours.innerHTML +=
        `<div class="list-item">
    <img class="small-img" src="img/Uhr.png">
    ${currentDate} ${startTime} - ${endTime} 
    </div>`;

    localStorage.setItem('html', myWorkingHours.innerHTML);
}

I have search 3 hours, but with not results

How to read data from fetch() getting a ReadableStream? [duplicate]

Using the fetch-function in a NodeJS application, I receive a response-object that contains a ReadableStream.

In my case, I want to catch errors and I try to figure out any response which could be part of the errornous request.

const res = await fetch(url);
if (!res.ok) {
      console.log('Status:', res.status);
      console.log('StatusText:', res.statusText);
      //console.log(res);
      const body = res.body;
      console.log(body);

The console.log on the body gives:

ReadableStream { locked: false, state: 'readable', supportsBYOB: false }

How can I use the ReadableStream to get a real string?

I was reading on Mozilla Database but I don’t understand their corresponding article especially not the example, which looks really weird.

How can I remove last * from each “organisations”: value from the string without using JSON.parse() and remove last , from [] using javascript?

let abc = '[{"userid":"88623619","organisations":"Imperial College London*Imperial College Healthcare NHS Trust*Imperial College Healthcare NHS Trust*Imperial College Healthcare NHS Trust*Milton Keynes Hospital NHS Foundation Trust*","oversightGroupRole":"Chair","oversightGroupMemberName":"Dr Ahmed Ahmed","oversightGroupType":"Steering Committee"},{"userid":"88624025","organisations":"Bangor University*Barnet, Enfield and Haringey Mental Health NHS Trust*Cambridge University Hospitals NHS Foundation Trust*","oversightGroupRole":"Public Member","oversightGroupMemberName":"Professor b b","oversightGroupType":"Advisory Group"},{"userid":"88623985","organisations":"Aberdeen And District Fibromyalgia Support Group*Additive Design Ltd*Altnagelvin Area Hospital*Ataxia UK*Tameside Hospital NHS Foundation Trust*","oversightGroupRole":"Chair","oversightGroupMemberName":"Chief TestTestRr TestTestRr","oversightGroupType":"Data Monitoring Committee"},]';

the Desried Result is

abc = '[{"userid":"88623619","organisations":"Imperial College London*Imperial College Healthcare NHS Trust*Imperial College Healthcare NHS Trust*Imperial College Healthcare NHS Trust*Milton Keynes Hospital NHS Foundation Trust","oversightGroupRole":"Chair","oversightGroupMemberName":"Dr Ahmed Ahmed","oversightGroupType":"Steering Committee"},{"userid":"88624025","organisations":"Bangor University*Barnet, Enfield and Haringey Mental Health NHS Trust*Cambridge University Hospitals NHS Foundation Trust","oversightGroupRole":"Public Member","oversightGroupMemberName":"Professor b b","oversightGroupType":"Advisory Group"},{"userid":"88623985","organisations":"Aberdeen And District Fibromyalgia Support Group*Additive Design Ltd*Altnagelvin Area Hospital*Ataxia UK*Tameside Hospital NHS Foundation Trust","oversightGroupRole":"Chair","oversightGroupMemberName":"Chief TestTestRr TestTestRr","oversightGroupType":"Data Monitoring Committee"},]';

My Code which is not working:

let abc = '[{"userid":"88623619","organisations":"Imperial College London*Imperial College Healthcare NHS Trust*Imperial College Healthcare NHS Trust*Imperial College Healthcare NHS Trust*Milton Keynes Hospital NHS Foundation Trust*","oversightGroupRole":"Chair","oversightGroupMemberName":"Dr Ahmed Ahmed","oversightGroupType":"Steering Committee"},{"userid":"88624025","organisations":"Bangor University*Barnet, Enfield and Haringey Mental Health NHS Trust*Cambridge University Hospitals NHS Foundation Trust*","oversightGroupRole":"Public Member","oversightGroupMemberName":"Professor b b","oversightGroupType":"Advisory Group"},{"userid":"88623985","organisations":"Aberdeen And District Fibromyalgia Support Group*Additive Design Ltd*Altnagelvin Area Hospital*Ataxia UK*Tameside Hospital NHS Foundation Trust*","oversightGroupRole":"Chair","oversightGroupMemberName":"Chief TestTestRr TestTestRr","oversightGroupType":"Data Monitoring Committee"},]';

    abc = abc.replace(/,(?=[^,]*$)/, '');

    let startIndex = 0;
    while ((startIndex = abc.indexOf('"organisations":', startIndex)) !== -1) {    
        let endIndex = abc.indexOf('*', startIndex + '"organisations":'.length);
        if (endIndex !== -1) {       
            abc = abc.slice(0, endIndex) + abc.slice(endIndex + 1);
        }
        startIndex += '"organisations":'.length;
    }

    console.log(abc);

Unable to use Javascript Library in Browser

I want to log all the events from a midi file.
I found a library that should do just that:
text

Problem is I can’t figure out how to use it in a website.
I’ve tried with a CDN from jsdeliver, however I get the error: “loadFile is only supported on Node.js”

I’ve tried with npm and vite build, however I still get the same error. The library uses the following codeCode

This library has 350 stars and seems like it should be of good quality,
If you could help me figure out how to correctly use it in a web project, that would be great. (in the browser)

Right now, I’m using the ES6 import:enter image description here

Not sure how I can use nodejs in the browser, or if there is something I can do to fix this, is this the fault of the library?

I can perfectly fine import local files for Threejs (for example) within the same project. Not sure why this dosen’t work…

Thanks for any help!

var user = Session.getActiveUser().getEmail(); doesnt get the email but gets an empty string?

So my code suppose to make me a tracking sheet of edits on the main sheet but when its gets the email it gives an empty email unless its my main email then its works for some reason here is the main function. and my friend from his pc it didnt even got “” the script didnt run so irdk the problems. btw i am new to this so dont make fun of me please.

function onEdit(e) {
  // Check if the event object is defined
  if (!e || !e.source) {
    // If the event object is not defined or does not have 'source' property, exit the function
    return;
  }

  var ss = e.source; // Get the active spreadsheet
  var trackingSheetUrl = "https://docs.google.com/spreadsheets/d/1VR1wc5xGtAB6dYmQCf9ChphwfHoOYI-7qKEjJEs42Lo/edit#gid=1175584031"; // Put the URL of your tracking sheet here
  var trackingSpreadsheet = SpreadsheetApp.openByUrl(trackingSheetUrl);
  var trackingSheet = trackingSpreadsheet.getSheets()[1]; // Assuming the tracking sheet is the first sheet

  var user = Session.getActiveUser().getEmail(); // Get the email of the user who made the change
  if (user == ""){
    user = "error";
  }
  var userLocation = searchDataColumnWithUser(trackingSheetUrl, user);
  if (userLocation) {
    // User found, increment the value
    var currentValue = userLocation.getValue();
    userLocation.setValue(currentValue + 1);
  } else {
    // User not found, create new row
    var lastUserRow = trackingSheet.getLastRow();
    var newUserRow = lastUserRow + 1;
    trackingSheet.getRange(newUserRow, 1).setValue(user); // Set username
    trackingSheet.getRange(newUserRow, 2).setValue(1);    // Set initial value as 1
    trackingSheet.getRange(newUserRow, 2).setValue(1);    // Set initial value as 1
  }
}

I suppose to get the email and update the sheet.

I have an error with my singleton design pattern

I am attempting to do a singleton pattern in javascript. I am getting error message “Uncaught TypeError: route_socket.getInstance is not a function”. I was wondering what am I doing wrong. I can copy and paste the pattern from a training guide and it works. But when I am trying it here, it gives the error. So I know the pattern works.

var route_socket = require([
    "esri/WebMap",
    "esri/views/MapView",
    "esri/layers/RouteLayer",
    "esri/rest/support/Stop"
  ],
  function(WebMap, MapView, RouteLayer, Stop) { //singleton design pattern
    var instance;

    class RouteSocket {#
      apiKey;

      constructor() {
        this.#apiKey = token.getAttribute("token");
        this.routeUrl = "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World";
        this.churches = [];
        this.stompClient = null;
        this.view = null;
        connect();
        this.origin = new Stop({
          geometry: {
            x: OX,
            y: OY
          },
          name: "Origin"
        })
        this.destination = new Stop({
          geometry: {
            x: DX,
            y: DY
          },
          name: "Destination"
        })
        addRandomChurch();
        addRandomChurch();
        addRandomChurch();
      }

      addRandomChurch() {
        var randomX = ((OX - DX) * Math.random()) + OX;
        var randomY = ((OY - DY) * Math.random()) + OY;
        var ChurchStop = { //Create a point
          x: randomX,
          y: randomY,
          name: "Church"
        };
        this.churchAdded(ChurchStop);
      }

      setView(view) {
        this.view = view;
        console.log("We have set the view");
        //check for churches already found and map them if they are there
        this.churches.forEach(this.addRoute(church));
      }

      connect() {

        var socket = new SockJS('/ws');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, this.onConnected, this.onError);
      }

      async addRoute(church) {
        let stops = [
          this.origin,
          church,
          this.destination
        ];

        let routeLayer = new RouteLayer({
          stops
        });
        view.map.add(routeLayer);
        await routeLayer.load();
        const results = await routeLayer.solve({
          apiKey
        });
        routeLayer.update(results);
        //            await view.goTo(routeLayer.routeInfo.geometry);
      }

      onConnected() {
        stompClient.subscribe('/topic/map/' + hobnobID.getAttribute("hobnobID"), this.onMessageReceived);
        synchroniseDataMapSocket.establishSocket(this);
      }

      onMessageReceived(payload) {
        var message = JSON.parse(payload.body);

        var ChurchStop = { //Create a point
          x: message.X,
          y: message.Y,
          name: "Church"
        };
        this.churchAdded(ChurchStop);
      }

      churchAdded(ChurchStop) {
        if (!this.view) {
          churches.add(ChurchStop);
          return;
        } else {
          this.addRoute(ChurchStop);
        }
        //else create stop on map
      }
    };

    function createInstance() {
      var object = new RouteSocket();
      return object;
    }

    return {
      getInstance: function() {
        if (!instance) {
          instance = createInstance();
        }
        return instance;
      }
    };
  });
route_socket.getInstance();

I am really grateful for any help I may receive. Thank you very much

Captivate SCORM in Moodle – JavaScript Error

I’m using Adobe Captivate Classic (2019).
I have created a SCORM project and it works great in Preview mode (Preview > Project menu).
I have created a variable named slideNum and a number of advanced actions. Again everything works well in preview mode. It also works well in my test in scorm.cloud.com as can be seen in the image where teh green tick appears after clicking the next button.

Works in scorm.cloud.com

I have JavaScript code as follows which is executed when I click the “next” button:

var currSlide = window.cpAPIInterface.getCurrentSlideIndex();
$("#icon_tick_slide" + currSlide + "c").css("visibility", "visible");

This displays an otherwise hidden tick mark when I click the next button.
The problem is that while this works in preview mode and in scorm.cloud.com, no matter what I try I cant get this to work on a moodle SCORM package. The tick simply wont show.

I’ve tried all sorts of combinations of SCORM exports from Moodle and code variations using window.onload and jQyery(document).ready even though none of the examples I’ve seen require this.

I’m using the documentation at https://helpx.adobe.com/captivate/classic/common-js-interface.html

Thanks for any help.

check if a specific div exists by class and data attribute without looping all the elements with that class

I have several divs in my UI with the same class. Each of them has a different data-id.
I want to check if one of the divs has a specific value for the data-id.
I can do it with .each() but was wondering if there is a way not to iterate every time on all the divs.
If I find a div (by class and data-id value) I need to manipulate its content. If I don’t find any div that satisfy the two criteria then I will perform some different activities.

What I have now (works but iterates every time the Dom)

let found = false;
$('.discussion').each(function(){
    if($(this).data("id")==myVariable){
        //I have found what I am looking for
        //do my stuff
        found = true;
    }
});
if(found===false){
    //I have not found what I was looking for
    //so I will add the div with that class and data-id
}

There can be even more then 10 divs with that class and this event will fire even 100 times a minute so performance may be impacted.

Is there a way to copy paste the contents of an HTML table into an Email Message?

I’m working on a locally hosted website using HTML, CSS, JS, Flask and SQLite3.

I want to create a functionality where the user is able to share the contents of a table via Email and I’ve created a ‘Share via Email’ button for the same.

When I run the program, the body of the email simply contains – ${inventoryTable} and the content is not displayed.

I know the data isn’t being retrieved correctly. How do I resolve this.

I don’t think I can attach the entire HTML page as its confidential, but the specific line of code I’m talking about is below…

<a href="mailto:?subject=Inventory Table &body=Inventory table details:%0D%0A%0D%0A ${inventoryTable}" target="_blank">Share via Email</a>

This line is supposed to retrieve data from a table wiht ID = “inventoryTable.”

This is what part of inventoryTable looks like –

<table id ="inventoryTable">
                <tr style="position: absolute; margin-top: -40px; z-index: 1;">
                    <th>Product ID</th>
                    <th>Product Name</th>
                    <th>Price(₹)/Unit</th>
                    <th>Quantity Available</th>
                    <th>Shelf Location</th>
                    <th>Accept Returns</th>
                    <th>Reorder Quantity</th>
                    <th>Edit Item</th>
                    <th>Delete Item</th>
                </tr>
                {% for item in data %}
                <tr>
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.price}}</td>
                    <td>{{item.quant_a}}</td>
                    <td>{{item.shelf}}</td>
                    <td>{{item.returns}}</td>
                    <td>{{item.quant_r}}</td>
                    <td>

I basically want the table headers and the rows to be copied into the email. I think I need to use JS for this but I’m not sure.

Help, please.

P.S. – I’m a 16yr old high-school kid doing this for a real-world client so could really use some help. (Also would really appreciate it if you could explain your solution a tad bit extra).

App renavigates to the logIn Page even if a new JWT token is regenerated

I am generating an accessToken for a user upon Login and a refreshToken
which helps to regenerate another accessToken for the user
if the user trys to refresh a page or the token times out.
but the problem is though these tokens are generated as it should be,
I am always redirected to Login page when I refresh the page
or when I click to access another Tab in the menue. What could
be the problem here.


//here is the Routes

const App = () => {
  return (

    <Routes>
      <Route path='registerPage' element={<RegisterPage />} />

      <Route path='logIn' element={<LogInPage />} />
      
      {/* Protected Routes */}
      <Route element={<PersistLogIn/>}>
      <Route element={<RequireAuth />}>

        <Route path='/' element={<Layout />}>

          <Route index element={<Home />} />

          <Route path='dashboard' element={<HomeLayOutt />} />

          <Route path='moneyIn' element={<MoneyIn />} />

          <Route path='moneyOut' element={<MoneyOut />} />
          <Route path='inventory' element={<Inventory />} />
    </Route> 
    </Route>
 </Routes>


//LogIn Page

const LogInPage = () => {
    const [username, setUserName] = useState("")
    const [password, setPassWord] = useState("")
    const {setAuth} = useAuth()


    const handleUser_Name =(e)=>{
        setUserName(e.target.value)
      }
      const handlePass_word = (e)=>{
        setPassWord(e.target.value)
      }
    
    const location = useLocation()

    const from = location.state?.from?.pathname || '/'

    const navigate = useNavigate()

    const goToRegister =()=>navigate('/registerPage')

        const handleLogIn=()=>{
        Axios.post('http://localhost:3500/auth', JSON.stringify({username, password}),
          {
            headers:{'Content-Type' : 'application/json'},
            withCredentials: true
          }
        )
        .then(res=> {    
            console.log(JSON.stringify(res?.data))
            console.log((res?.data))
            const accessToken = res?.data?.accessToken
            setAuth({username, password, accessToken})

            setUserName('')
            setPassWord('')

            navigate(from, {replace: true})
            
        }).catch(err =>{console.log(err)})
    }
}

//Context API(AuthProvider)

import { createContext, useState } from "react";

const AuthContext = createContext({})

export const AuthProvider =({children})=>{
   const [auth, setAuth] = useState({})
   console.log(auth)

  return(
  <AuthContext.Provider value={{auth, setAuth}}>
    {children}
   </AuthContext.Provider>
  )
}
export default AuthContext

//useAuth

import { useContext } from "react";
import AuthContext from "../context/AuthProvider";

const useAuth = () =>{
    return useContext(AuthContext)
}
export default useAuth

//RequireAuth

import {useLocation, Navigate, Outlet} from 'react-router-dom'
import useAuth from '../hooks/useAuth'

//check if the user is logged in or not
//this is a component that will help us protect our routes
const RequireAuth = () =>{
    const {auth} = useAuth()
    const location = useLocation()
   console.log(auth)
     return(
        auth?.username ? <Outlet/> : <Navigate to='/login' state={{from: location}} replace/>
     )
}
export default RequireAuth

//PersistLogIn

const PersistLogIn = () => {
    const [isLoading, setIsLoading] = useState(true)
    const refresh = useRefreshToken()

    const {auth, persist} = useAuth()

    useEffect(()=>{

        const refreshTokenVerify = async () =>{
            try{
               
               await  refresh()
            }
            catch(err){
                console.error(err)
            }
            finally{
                setIsLoading(false)
            }
        }

        !auth?.accessToken ? refreshTokenVerify() : setIsLoading(false)
    },[])

    useEffect(()=>{
        console.log(`isLoading: ${isLoading}`)
        console.log(`aTh: ${JSON.stringify(auth?.accessToken)}`)
    },[isLoading])

  return (
    <>
                {isLoading
                    ? <p>Loading...</p>
                    : <Outlet />
            }
    </>
  )
}

export default PersistLogIn





//BackEnd

//authController

const handleUserLogIn = async (req, res)=>{
    const {username, password} = req.body
    if(!username || !password) return res.status(400).json({'message':'username or password is required'})//Bad Request

    const foundUserData = await User.findOne({username}).exec();
    console.log(foundUserData) 

    if(!foundUserData) return res.sendStatus(401)//Unauthorized

    const validPassword = await bcrypt.compare(password, foundUserData.password)
    if(!validPassword){
        return res.sendStatus(401)//Unauthorized
    }else{
      //create the JWT
      const accessToken= jwt.sign({'username':foundUserData.username}, 
      process.env.ACCESS_TOKEN_SECRET, {expiresIn: '30s'})
      const refreshToken= jwt.sign({'username':foundUserData.username}, 
      process.env.REFERESH_TOKEN_SECRET, {expiresIn: '5m'})

      //save refreshToken with current user
      foundUserData.refreshToken = refreshToken
      const result = await foundUserData.save()
      console.log(result)
      
      //create a secured cookie with refreshToken
      res.cookie('jwtToken',refreshToken, {httpOnly: true, maxAge: 300000} ) //secure: true
      
      //res.cookie('token', accessToken, {httpOnly: true, maxAge: 20000})

      //Send access Token to user
      res.json({accessToken})
    }
        
}

module.exports={handleUserLogIn}

//refreshTokenController

const handleRefreshToken = async(req, res)=>{
  const cookies = req.cookies
  console.log(cookies.jwtToken)

  if(!cookies?.jwtToken) return res.sendStatus(401)//unauthorized //.jwt
  console.log(cookies.jwtToken)
  const refreshToken = cookies.jwtToken

  const foundUserData2 = await User.findOne({refreshToken}).exec()
  if(!foundUserData2) return res.sendStatus(403)//Forbidden

  //evaluate JWT
  jwt.verify(refreshToken, process.env.REFERESH_TOKEN_SECRET, 
     (err, decoded)=>{
        if(err || foundUserData2.username !== decoded.username)return res.sendStatus(403);//forbidden
        //another accessToken is created
        const accessToken = jwt.sign(
        {'username':decoded.username}, 
        process.env.ACCESS_TOKEN_SECRET, 
        {expiresIn: '30s'}
        )

      res.json({accessToken})
     })
}
module.exports = {handleRefreshToken}