React helmet doesn’t execute the script tag in the right order

There are two external resources and one custom JS file to load up into the component. The custom JS file should be executed only after the external resources. However, it doesn’t really work this way even though defer keyword has been put on. It seems like the custom JS file is executed first. I wonder what’s going wrong with this approach?

import React, { Fragment, useEffect, useRef } from "react";
import "./Home.css";
import { Helmet, HelmetProvider  } from 'react-helmet-async';
import ShowCase from "./ShowCase";
import BookCarousel from "./BookCarousel";
import Testimonial from "./Testimonial";
import SignUp from "./SignUp";
import Contact from "./Contact";
const Home = () => {

  return (
    <HelmetProvider>
        <Helmet>
            <script type="text/javascript" defer src="https://code.jquery.com/jquery-1.12.4.min.js" ></script>
            <script type="text/javascript" defer src="https://unpkg.com/scrollreveal" ></script>
            <script type="text/javascript" defer src="./carousel.js"></script>
        </Helmet>
        <ShowCase />
        <BookCarousel />
        <Testimonial />
        <SignUp />
        <Contact />
    </HelmetProvider>
  );
};
export default Home;

How to exit nested while loop

var userName = input.question('Please enter your name: ');
console.log('nHi ' + userName + ', please select your choice:');
var choice = input.question('1. Display Name 2. Display Age');
while (choice == 1 {
 console.log ("Hello");
 var choice = input.questionFloat('1. Display Name 2. Display Age');
}
while (choice == 2 {
 console.log ("Hello");
  var subChoice = input.question('1. Display date 2. Display time');
  while (subChoice == 1) {
             console.log ("Hello");
  }
  while (subChoice == 2) {
             console.log('nHi ' + userName + ', please select your choice:');
             var choice = input.questionFloat('1. Display Name 2. Display Age');
  }
}

The first block of code is asking the user their name, after which the user will be required to enter either choice 1 or 2.

The choice that the user chose will be stored in the “choice” variable. I have both “choice” as well as “subChoice”. “subChoice” comes after the user select “choice”. In this case, in order to access the subChoice 1 or 2, the user will have to select choice 2 first. If I want to exit the subChoice, I would have to select subChoice 2 which will bring me back to the choices for choice 1 & 2.

However, the problem that I am facing is that after returning to choice 1 or 2, the variable userName does not contain anymore value or string. In addition, when I select other choices i.e choice 1, it does not do anything but re-prompting me the same thing with no userName and loops in the subChoice == 2 itself.

Is there any solution to this?

Vue.js + Creating async contructor Class and accessing the data

I am a newbie and need help. I have created a class and i want to initialize my data property ‘Filters’ on created function with the value returned from the constructor of the class ‘Filters’
However as i am calling an async webapi it does not return anything into my property. How can i achieve this using class

<script>
export default {
 data() {
  return {
  Filters : [];
};
},
methods: {},
created () {
   this.Filters = new Filters(); // returns promise pending
}
};
class Filters
{
    constructor()
    {
        this.filters = this.loadFilters();
    }

    async loadFilters ()
    {
        const query = `?$select=*&$filter=_new_table_value eq ${window.parent.Xrm.Page.data.entity.getId().replace(/[{}]/g, "")}&$orderby=ice_name asc`;
        var result = await window.parent.Xrm.WebApi.retrieveMultipleRecords('ice_filterstable', query);
        console.log(result); // this does return values 
        return result;
    }
}

enter image description here

pdf.js upload second file but show first content, how to show second content

I want show second upload file content in canvas,but it always show first one.

This is my html:

<input type="file" id="myfile" name="myfile" value="upload">
<div>
<button id="prev">prev</button>
<button id="next">next</button>
<span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
</div>
<canvas id="the-canvas"></canvas>

canvas first img will be right, but others are wrong.

This is my js:

var pdfjsLib = window['pdfjs-dist/build/pdf'];      
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://mozilla.github.io/pdf.js/build/pdf.worker.js';

var pdfDoc = null,
pageNum = 1,
pageRendering = false,
pageNumPending = null,
scale = 1.5,
canvas = document.getElementById('the-canvas'),
ctx = canvas.getContext('2d');


$("#myfile").on("change", function (e) {
var file = e.target.files[0];
var fileReader = new FileReader();

fileReader.onload = function () {

var pdfData = new Uint8Array(this.result);
// Using DocumentInitParameters object to load binary data.
var loadingTask = pdfjsLib.getDocument({data: pdfData});



function renderPage(num) {
pageRendering = true;
// Using promise to fetch the page
pdfDoc.getPage(num).then(function(page) {
var viewport = page.getViewport({scale: scale});
canvas.height = viewport.height;
canvas.width = viewport.width;

// Render PDF page into canvas context
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
var renderTask = page.render(renderContext);

// Wait for rendering to finish
renderTask.promise.then(function() {
pageRendering = false;
if (pageNumPending !== null) {
// New page rendering is pending
renderPage(pageNumPending);
pageNumPending = null;
}
});
});


document.getElementById('page_num').textContent = num;
}


function queueRenderPage(num) {
if (pageRendering) {
pageNumPending = num;
} else {
renderPage(num);
}
}


function onPrevPage() {
if (pageNum <= 1) {
return;
}
pageNum--;
queueRenderPage(pageNum);
}
document.getElementById('prev').addEventListener('click', onPrevPage);


function onNextPage() {
if (pageNum >= pdfDoc.numPages) {
return;
}
pageNum++;
queueRenderPage(pageNum);
}
document.getElementById('next').addEventListener('click', onNextPage);


pdfjsLib.getDocument({data: pdfData}).promise.then(function(pdfDoc_) {
pdfDoc = pdfDoc_;
document.getElementById('page_count').textContent = pdfDoc.numPages;

// Initial/first page rendering
renderPage(pageNum);
});


};


fileReader.readAsArrayBuffer(file);



});

pdf.js upload second file but show first content, how to show second content,thanks a lot
pdf.js upload second file but show first content, how to show second content,thanks a lot
pdf.js upload second file but show first content, how to show second content,thanks a lot

Convert Unix Date and Time to Local Time with JavaScript (React)

I’m trying to convert unix timestamp to local date in a react project. Below is the function that I’m using:

function convertDate(unixDate) {
        const d = new Date(unixDate * 1000);
        const day = d.toLocaleString(d.getDate())
        return(day);
    }

The date I’m getting is not acurate. For example is we run convertDate(1657745369979.82) we should get the date ’07/13/2022 8:49:29 PM’. However the date that I’m actually getting is ’11/10/54501, 8:59:39 AM’

Can’t hear voice and sound while sharing screen in Agora.io

I have some issues with screen sharing. I can’t hear any sounds from viewer site. What can i do this for? I am new to this. Source from dennis ivy:https://www.youtube.com/watch?v=QvNzL_FmzLQ&t=33273s

let toggleScreenShare = async() => {
if (sharingScreen){
    sharingScreen = false
    await rtcClient.publish([localScreenTracks])
    toggleVideoShare()
    
    document.getElementById('screen-btn').innerText ='Share screen'

}else{
    sharingScreen = true
    document.getElementById('screen-btn').innerText ='Share camera'
    localScreenTracks = await AgoraRTC.createScreenVideoTrack()
    document.getElementById('video__stream').innerHTML =''
    
    let player = document.getElementById(`user-container-${rtcUid}`)
    if(player != null){
        player.remove()
    }
    player = `<div class="video-container" id="user-container-${rtcUid}">
    <div class="video-player" id="user-${rtcUid}"></div>
    <div class="live-location">
    <span class="live-tag">LIVE</span></div>
    
    </div>
    </div>
    `
    document.getElementById('video__stream').insertAdjacentHTML('beforeend', player)
    localScreenTracks.play(`user-${rtcUid}`)
    await rtcClient.unpublish([localTracks[0], localTracks[1]])
    await rtcClient.publish([localScreenTracks])
}

How can I use add_experimentail_option in javascript?

I wanted to use selenium in javascript,
but I there are some error codes when I ran the code.
In python, I avoid this errors by this code:

options = wd.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-logging"])

Is there any way to solve this problem in javascript?
This is our error code:

[33448:11152:0715/135211.483:ERROR:device_event_log_impl.cc(214)] [13:52:11.483] USB: usb_device_handle_win.cc:1048 Failed to read descriptor from node connection:

How can I assign an object’s property to a variable ..,?

I have five variables each contain an editable div element .. I want to create an object with five properties then assign these properties to the innerText of the five variables ..

let First_name = document.querySelector(".firstName")
let Second_name = document.querySelector(".secondName")
let Mars_name = document.querySelector(".marsName")
let Email = document.querySelector(".phoneOrEmail")
let Password = document.querySelector(".password")

let form = {}

form.First_name = First_name.innerText;
form.Second_name = Second_name.innerText;
form.Mars_name = Mars_name.innerText;
form.Email = Email.innerText;
form.Password = Password.innerText;
                        
console.log(form);

when I print the object in the console, each property is assigned a value ” “.

how to convert this javascript code to reactjs?

const mobileMenuOpenBtn = document.querySelectorAll(‘[data-mobile-menu-open-btn]’);
const mobileMenu = document.querySelectorAll(‘[data-mobile-menu]’);
const mobileMenuCloseBtn = document.querySelectorAll(‘[data-mobile-menu-close-btn]’);
const overlay = document.querySelector(‘[data-overlay]’);

for (let i = 0; i < mobileMenuOpenBtn.length; i++) {

// mobile menu function
const mobileMenuCloseFunc = function () {
    mobileMenu[i].classList.remove('active');
    overlay.classList.remove('active');
}

MobileMenuOpenBtn[i].AddEventListener('click', function () {
    mobileMenu[i].classList.add('active');
    overlay.classList.add('active');
});

mobileMenuCloseBtn[i].addEventListener('click', mobileMenuCloseFunc);
overlay.addEventListener('click', mobileMenuCloseFunc);

}

NodeJS + Express: Server cannot resolve GET, PUT, POST, or DELETE requests (Status 404)

server.js

const express = require('express')
const dotenv = require('dotenv').config()
const port = process.env.PORT ||9999
const goals = require('./routes/goalRoutes')
const app = express()

app.use('/api/goals', goals)
app.listen(port, () => console.log(`Server started on port ${port}`))

goalRoutes.js defines a route api/goals

const express = require('express')
const router = express.Router()
const { createGoal, getGoals, updateGoal, deleteGoal, } = require('../controllers/goalController')

router.route('/').post(createGoal).get(getGoals)
router.route('/:id').put(updateGoal).delete(deleteGoal)

module.exports = router

goalController.js gives functionality to that route

//@desc     Create goal
//@route    POST /api/goals
//@access Private
const createGoal = (err, req, res, next) => {
    res.status(200).json({message: "Create goal"})
}

//@desc     Get goals
//@route    GET /api/goals
//@access Private
const getGoals = (err, req, res, next) => {
    res.status(200).json({message: "Read goals"})
}

//@desc     Update goal
//@route    PUT /api/goals:id
//@access Private
const updateGoal = (err, req, res, next) => {
    res.status(200).json({message: `Update this goal: ${req.params.id}`})
}

//@desc     Get goals
//@route    DELETE /api/goal/:id
//@access Private
const deleteGoal = (err, req, res, next) => {
    res.status(200).json({message: `Delete this goal: ${req.params.id}`})
}

module.exports = {
    createGoal,
    getGoals,
    updateGoal,
    deleteGoal,
}

I have created a route (intended as /api/goals) and controllers for that route. I then used the controllers found in goalController.js to handle GET, PUT, POST, and DELETE requests and connected that to goalRoutes.js.

Using Postman for testing, I can only resolve these requests with a 404 status.

My initial thought process was that I didn’t correctly import the controller functions into goalRoutes.js, but I seem to have exported them as an object just fine and Node doesn’t seem to have an issue with anything at runtime.

I used to have the body of the controllers’ functions within the callback functions of router.get, router.post, router.put, and router.delete but that was really messy. I would strongly prefer not to go back to that mess.

I am at a loss. What’s stopping the callback functions of router.route to use the controller functions? Why does Postman receive 404?

I apologize if my terminology sucks. I’m a total beginner at Javascript.

createAsyncThunks first promise is fulfilled, but subsequent promises are always rejected

I have a saveTrip function that is a redux async thunk. However, i am getting very weird behavior as only my first promise is resolved as “fulfilled” and every promise after that is “rejected”

export const saveTrip = createAsyncThunk(
    'trip/saveTrip',
    async (payload, thunkAPI) => {
        const trip = thunkAPI.getState().trip
        const result = await fetch(
            'http://localhost:5000/savetrip', {
            mode: 'cors',
            credentials: 'include',
            method: "post",
            body: JSON.stringify({ trip }),
            headers: {
                'Content-Type': 'application/json'
            },
        })
        const response = await result.json()
        return response
    }
)

Whats more unusual is that i stumbled upon a bandaid fix by implementing debounce like so :

export const saveTrip = createAsyncThunk(
    'trip/saveTrip',
    debounce(async (payload, thunkAPI) => {
        const trip = thunkAPI.getState().trip
        const result = await fetch(...)
        const response = await result.json()
        return response
    }, 5000)
)

Debounce doesnt actually “work” as i expect debounce to, but now, every promise is getting fulfilled with the expected data in the responses. Im pretty sure this is not a proper solution but I am very confused as to what’s happening.

My goal is to just save my current state into my DB and i just call saveTrip whenever a reducer that changes my state is dispatched.

How can we check key avaibality in objects?

const student= [
      {
        student_id: 0,
        name: "Rhoda Salas",
        checked:"checked"
      },
      {
        student_id: 1,
        name: "Jewell Avery"
      },
      {
        student_id: 2,
        name: "Susanne Harris",
        checked:"checked"
      }
    ]
    
console.log(student)

As we know that, I have student variable which contain array of object.
Now, I want to check (find) or count which object has contained checked key.
So How can I find and how many ways ?

Azure App Configuration client library – caching of getConfigurationSetting

I’m using the library @azure/app-configuration in my Angular web site and it works great. I used it for feature flagging.
I run into the issue, that when I change a feature flag state (enabled to disabled or vice versa), this is not reflected in the website.

When I check the Network tab, I can see a request, but its status is “from disk cache”.
request in network tab
In the response headers, I don’t see any cache control headers, but I do see a LastModified header. It seems that this may impact caching.

I can’t find any option or setting in the AppConfigurationClient or the method getConfigurationSetting to disable caching or refresh. I tried the option “acceptDateTime” set to new Date() but that doesn’t make any difference. Also been playing around with other options, no luck

Alternatively, would it be possible to clear the cache for this URL (https://{{name}}.azconfig.io)?

remove timezone in my random date generator in javascript

This is my code. I make it random but the timezone is always in there and i dont know how to disappear the timezone, can someone help me with this I’am beginner in this thanks

var startDate = new Date("1990-01-01"); //YYYY-MM-DD
var endDate = new Date("2022-01-01"); //YYYY-MM-DD

function formatDate(date) {
  const year = date.getFullYear();
  /* getMonth returns dates from 0, so add one */
  const month = date.getMonth() + 1;
  const day = date.getDate();
  
  return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}

var getDateArray = function(start, end) {

  return new Date(
    start.getTime() + Math.random() * (end.getTime(0) - start.getTime(0))
  );

}
var dateArr = getDateArray(startDate, endDate);


console.log(dateArr);