Multiple redirects using React router dom

I’m using React Router to redirect to a login page when user is not logged in, like this:

return (
    <main className="App  relative">
      <Routes>
        <Route path="/" element={<AuthLayout />}>
          <Route path="/" element={<Login />} />
        </Route>

        <Route path='/*' element={<PrivateRoute/>}>
          <Route path="/*" element={<Layout />}>
            <Route path="dashboard" element={<Dashboard />} />
          </Route>

          <Route path="/*" element={<Layout />}>
            <Route path="timeline" element={<TimeLine />} />
          </Route>
        </Route>
      </Routes>
    </main>
);

this is my PrivateRoute:

const PrivateRoute = () => {    
    const [currentUser] = useAtom(currentUserAtom);
    const isAuth = (currentUser && currentUser.token);

    const prevLocation = useLocation();
    var redirectTo = `/login?redirectTo=${prevLocation.pathname}`;
    console.log(redirectTo);        
    return isAuth ? <Outlet /> : <Navigate to={redirectTo} />;
}

export default PrivateRoute;

The problem is that the PrivateRoute executes 3 times, with these results:

/login?redirectTo=/dashboard 
/login?redirectTo=/login
/login?redirectTo=/login

And the final redirect page is http://localhost:5173/login?redirectTo=/login instead of http://localhost:5173/login?redirectTo=/dashboard

What’s wrong?

Is it OK to add Google Tag codes onto Github Repository?

Stuff like API keys uploaded to Github Repository could cause some of the devastating problems, so I want to know if the Google Tag codes like( could also become a source of problems.

Example Google Tag code:

<--Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-xxxxxxxxxx"></script> <script> 
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);} gtag('js', new Date()) ;
gtag('config', 'G-xxxxxxxxxx') ;
</script>

custom created cron function is not working

i have attached the following function with my cron which hits every 10 mins , the problem is that

the following function is not running on my stage environment (was running perfectly fine on my local). I believe that the problem resides within function _fetchIdToProcess , since the whole code is dependent on the length of the array . Also using bluebird for “promosifying” redis calls

const CacheUtils = require('../../utils/cache-utils');
const ESUtils = require('../../utils/es-utils');
const esClient = ESUtils.initializeESConnection();


/**
 * @description the following cron fetches all the docs from events needed to be merged on the basis of 
 * fileGroupId , after merging all the "dangling docs" will be deleted 
 */


module.exports = class MergeFileEvents {
  static async mergeFileEvent() {
    const client = await CacheUtils.getClient();
    const fileGroupIds = await this._fetchIdToProcess('file_upload*');

    if (fileGroupIds.length > 0) {

      // locking the fileGroupIds , for preventing dirty reads

      await client.saddAsync('processing_file_ids',fileGroupIds);

      // main implementation for merging docs
      await this._mergeDocs(fileGroupIds);

      // releasing the locks (deleting the ids) 
      await this._releaseLockFileGroupIds(fileGroupIds)
    }
  }


  static async _fetchIdToProcess(pattern) {
    const client = await CacheUtils.getClient();
    let keys = [];
    let cursor = '0';

    do {
      const reply = await client.scanAsync(cursor, 'MATCH', pattern, 'COUNT', 1000);
      cursor = reply[0];
      keys = keys.concat(reply[1]);
    } while (cursor !== '0');

    const processingIds = await client.smembersAsync('processing_file_ids') || [];

    return keys.filter(key => !processingIds.includes(key));
  }


  static async _mergeDocs(fileGroupIds) {
    const date = new Date();
    const client =await CacheUtils.getClient();
    for (let id of fileGroupIds) {
      const eventIds = await client.smembersAsync(id);

      if (eventIds.length <= 1) continue; // no need to merge in this case 
    
      const  body  = await esClient.search({
        index: `events_${date.toJSON().split('T')[0]}`,
        body: {
          query: { ids: { values: eventIds } },
          _source: ['file.id'],
          size: eventIds.length
        }
      });
      
      const fileIdsPayload = await Promise.all(eventIds.map(async (id) => {
        const createdAt = await client.getAsync(id); 
          return{
             id: body.hits.hits.find(hit => hit._id == id)?._source.file.id,
             createdAt
          }
      }));

      const lastUpdate = fileIdsPayload.reduce((max, curr) => {
        return new Date(curr.createdAt) > new Date(max.createdAt) ? curr : max;
      }).createdAt;


      await esClient.update({
        index: `events_${date.toJSON().split('T')[0]}`,
        id: eventIds[0],
        body: {
          doc: {
            files: fileIdsPayload,
            updatedAt: lastUpdate
          }
        }
      });

      const deleteEvents = eventIds.slice(1).map(id => ({
        delete: {
          _index: `events_${date.toJSON().split('T')[0]}`,
          _id: id
        }
      }));

      await esClient.bulk({
        body: deleteEvents
      });

    }
  }

  static async _releaseLockFileGroupIds(fileGroupIds) {

    const client =await CacheUtils.getClient();

    // deleting fileGroupIds from processing set
    await client.sremAsync('processing_file_ids',fileGroupIds);

    // deleting timestamps of eventId
    for (let id of fileGroupIds) {
      await client.delAsync(id);
    }
  }
}

What are the VarScopedDeclarations and VarDeclaredNames of a non-empty block statement according to ECMAScript spec?

I’m studying the ECMAScript spec to find out what the expected behavior of vars statements inside a block is according to the spec:

function test() {
    console.log('before block', bar);
    {
      console.log('in block before declaration', bar);
      var bar = 30;
      console.log('in block after declaration', bar); 
    }
    console.log('after block', bar);
}

test();

The DeclarationInstantiation semantics indicate that variables declared with var are collected by VarDeclaredNames and VarScopedDeclarations semantics. But the spec only defined the semantics for empty block without any statement:

VarDeclaredNames in spec

How could I know what the VarDeclaredNames and VarScopedDeclarations of Block { statementList } should be?

I found other semantics include Block { statementList }, so I expect the VarDeclaredNames and VarScopedDeclarations may consist of it too, or how should the implementations treat block without instructions?

block statement syntax example

For the web with javascript, is it possible to style or customize the “Open file” dialog window to suite the style of our website application?

We have an html & javascript application with a button that opens a file dialog window allowing the user to select files. We would like the style the open file dialog interface window itself. Is this even a possibility? Instead of the standard square file open dialog window we want rounded corners and a blue background.

Searching google for javascript customize open file dialog did not return any relevant results.

Distinguish between a scanner input and keyboard input in Javascript

I have parcel search input, where you can search parcels with a barcode, you can enter the barcode both with the keyboard and with the scanner. I need to clear the old input value when the user scans a new one.

I work with Javascript and As far as I can see, javascript can’t distinguish between a scanner input and keyboard input, so I use time base. At the moment I don’t have a scanner and I use a phone scanner with the Barcode2win app when I test my script it works well, but when a customer checks out with a scanner it doesn’t work, it just prints the barcode’s only last 4 number.

This is my script

document.addEventListener("DOMContentLoaded", function () {
    const input = document.getElementById("searchParcels");
    let lastKeyTime = 0;
    let inputBuffer = "";
    const barcodeThreshold = 50; // Time threshold for detecting barcode scanner input
    const typingDelay = 200; // Delay to determine if it's keyboard input
    let typingTimer;

    function processInput(page = 1) {
        let search_string = input.value;
        
        fetch(
            `${searchRoute}/search?query=${encodeURIComponent(
                search_string
            )}&page=${page}`,
            {
                headers: {
                    "X-Requested-With": "XMLHttpRequest",
                },
            }
        )
            .then((response) => response.text())
            .then((data) => {
                document.querySelector(".parcels-list-container").innerHTML =
                    data;
                attachPaginationLinks(search_string);
            })
            .catch((error) => console.error("Error:", error));
    }

    function clearInput() {
        input.value = "";
        inputBuffer = "";
    }

    function attachPaginationLinks(query = "") {
        const paginationLinks = document.querySelectorAll(
            ".parcels-list-container .pagination a"
        );
        paginationLinks.forEach((link) => {
            link.addEventListener("click", function (event) {
                event.preventDefault();
                const url = new URL(this.href);
                const page = url.searchParams.get("page");
                processInput(page);
            });
        });
    }

    input.addEventListener("keydown", function (e) {
        const currentTime = new Date().getTime();
        const timeDifference = currentTime - lastKeyTime;

        if (timeDifference < barcodeThreshold) {
            if (e.key.length === 1) {
                inputBuffer += e.key;
            }

            if (inputBuffer.length > 0) {
                clearInput();
                input.value = inputBuffer;
                inputBuffer = "";
                processInput();
            }
        } else {
            
            clearTimeout(typingTimer);
            typingTimer = setTimeout(() => processInput(), typingDelay);
            inputBuffer = "";
        }

        lastKeyTime = currentTime;
    });
});

I am creating a multiple choice question exam project using radio button using js

I am creating a multiple choice question exam project using radio button but there is problem in clicking the submit button and going to next question, getting correct or incorrect as result

here is code of HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MCQ Quiz</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
   
   <div class="quiz_container">
     <form id="quiz_form" onsubmit="return submitquiz(event)"> 
       <div class="question">
         <h1> Sample question for quiz </h1>
          <p id="que-text">  1. What is the capital of the india ?</p>
           <div class="choices">
           <label >
              <input type="radio" value="0" name="choice" > Mumbai<br>
            </label>   
            <label >
                <input type="radio" value="1" name="choice"> Kolkata <br>
            </label>   
           <label >
              <input type="radio" value="2" name="choice"> Delhi <br>
           </label> 
            <label > 
              <input type="radio" value="3" name="choice"> Chennai <br>
            </label>
          </div>
            <div> <p id="result"> </p> </div>

            <button type="submit"> Submit </button>
      </form>

here is css

body
 {
  background-color: #ffffff;
  font-family: Arial, Helvetica, sans-serif;
  display: flex;

}

.quiz_container
{
    width: 600px;
    margin: auto;
    padding: 2em;
    background-color: #a9dcf0;
    border-radius: 10px;
    box-sizing: border-box;
    box-shadow: 0 0 5px black;
}

.question
{
  margin-bottom: 15px;
}

.choice
{
  display: flex;
  flex-direction: column;
}

label
{
  font-size: 1em;
}

button 
{  
  background-color: #28a745;
  color: antiquewhite;
  border: none;
  border-radius: 5px;
  cursor: pointer ;
  display:inline-block;
  padding: 10px 20px;
}


button:hover
{
  background-color: #218835;
}

#result
{
  margin-top: 15px;
  font-size: 1.2em;
} 

here is js

 const ques=[
     // questions 
 
  
    {question: "2. How many months are there in year ?",
     choices:[" 11", "13", "12", "10"],
     correct: "2"  },

    {question:"3. The largest contry of world (Area wise) ?",
     choices:["Russia", "Canada", "India ", "Brazil"],
     correct:" 0" },

   // {question:" 4.  ",
     //choices:[ " ", " ", " ", " ",],
     //correct: " "  },
    ];

    let currentQue= 0;
    let currentAns= 0;

    function showQue ()
    {
        const queText= document.getElementById("que-text");
        queText.textContent= question[currentQue].question;
    

    const choices= document.querySelectorAll(".choice");
    choices.forEach((choice,index)=> {choice.textContent= question[currentQue].choices[index];});

    const result = document.getElementById("result");
    result.textContent="";
    }

    function checkAnswer(selected) {
        const result = document.getElementById("result");
        if (selected === ques[currentQue].correct) 
       {
          result.textContent = "It is Correct!";
          correctAnswers++;
        }
         else 
        {
          result.textContent = " It is Incorrect!";
        }
      
        setTimeout(() => {
          currentQue++;
      
          if (currentQue< ques.length)
         {
            showQuestion();
          } 
          else 
          {
            const quizContainer = document.querySelector(".quiz_container");
            quizContainer.innerHTML = `<p>You got ${correctAnswers} out of ${ques.length} questions.</p>`;
          }
        }, 2000);
      }
      
      showQuestion();  

i am expecting that after submitting correct answer it will show as it is Correct! and if wrong than it is Incorrect!. than next question and so on . after completing all the questions it will show score. but i am stuck at Submit button and process after it.

Why moments comparison is wrong?

I have two valid Moment instances: endDateTime and startDateTime. endDateTime is earler than startDateTime. Why isBefore always returns false and isSame always returns true?

Instances created by 3rd party library ‘Angular Material Datepicker’.

Example of objects comparison:

enter image description here

Cookie management and consent in ASP.NET MVC 4.8

I’d like to get some context from people that have previously implemented existing libraries/tools regarding cookie management in .net 4.8 applications. We currently have a site where we show a banner that asks the user to accept cookies.

We would like to extend the cookie acceptance for the user to allow them to accept/reject cookies based on their preference (where applicable). We make use of js-cookie in the project already to handle setting/retrieving client side cookies. There are also server cookies used for session and user identification.

A general audit of cookies used was done using the scan provided by CookieYes (https://www.cookieyes.com/).

I am wanting to know more about using any light-weight libraries that can be easily integrated into a .net 4.8 project (potentially covering the client-side and server-side), without much intrusion or customization.

Paying for a service is acceptable if there are no free solutions available. Ultimately, I am wanting to use some Javascript (or Nuget package, if applicable) that identifies and classifies the cookies by their correct category on page load, and enables me to present a modal to the user on button click for them to accept or reject cookies they’re able to. I imagine their choices should be stored in a database for subsequent logins.

Outside of using a full on Consent Management Platform (want as much control as possible), are there more streamlined ways to introduce this into an existing application? I pose this question out of curiosity as I investigate myself.

So far, I’ve landed on this resources that look promising, but have yet to try the libraries out:
21 Top Free JavaScript Libraries for GDPR-Compliant Cookie Management. I do not want to have to manually go into the cookies and classify each one if it can be helped.

Outside of client-side libraries, are there any Nuget packages for .net 4.8 that can be leveraged to achieve the same thing? Some of the nuget packages I’ve landed on personally do not seem that actively used and makes me question their practicality/longevity.

As I continue investigating, will be revisiting this post to provide details on solutions I’ve found as well.

How can I use Umami analytics across subdomains?

(Already asked this question at Webmasters Stack Exchange, but I’m not sure that’s the right place for it)

I’m having trouble setting up Umami analytics with subdomains. Here’s my scenario:

At example.com, I serve my product website that advertises my service. This site includes my marketing content and ad landing pages, etc. However, serve my actual webapp over at app.example.com. I want to track users across the boundary between my app and my website, so I can, for example, see user journeys from the website to the app.

I tried just using the same Umami website ID on the root site and subdomain. As far as I can tell, though, Umami doesn’t differentiate between https://example.com/ and https://app.example.com/—they both appear as /.

I found many similar questions, but they all are specific to Google Analytics.

I’m new to Umami and analytics in general. What am I missing here? Do I need to create a custom tracker function for this usecase, sending a custom value for url that includes the subdomain? Or is this an unsupported setup?

NextJS not rendering Hero component on full screen

I am creating a static site with NextJS (seems too much just for a static site I know but I might have to expand this in the future). Anyways, right now I am keeping it simple with a few animations. The problem is I have created a Hero component which should take up the entire height of the screen. I used min-h-screen in the main tag and h-screen for the Hero component.

Here’s the index.js:

import Hero from "@/components/Hero";
import About from "@/components/About";

export default function Home() {
  return (
      <main className="flex flex-col min-h-screen w-full items-center">
        <Hero />
        <About />
      </main>
  )
}

Hero.js

import Lausanne from 'next/font/local';
import Juana from 'next/font/local';
import Image from "next/image";
import gobhiPic from '../assets/fried veg.png';
import { HiMiniArrowUpRight } from "react-icons/hi2";
import { motion } from "framer-motion";

const lausanne = Lausanne({ src: '../assets/Lausanne-Regular.otf' });
const juana = Juana({ src: '../assets/Juana-Medium.otf' });

const Hero = () => {
  return (
    <div className="flex h-screen w-full items-center overflow-hidden">
      <motion.div 
        initial={{ opacity: 0, x: 0, y: 150 }}
        animate={{ opacity: 1, x: 0, y: 0 }}
        transition={{ duration: 1.5 }}
      >
        <div className="flex p-24 justify-center items-center text-black-ribbon">
          <h1 className={`text-10xl ${juana.className}`}>
            Large Name
            <p className={`text-sm px-2 mt-3 md:mt-0 md:text-base md:px-2 ${lausanne.className}`}>
              TAGLINE
            </p>
            <button href="#menu" className={`text-xl md:text-2xl mt-10 p-2 flex items-center bg-transparent transition-colors duration-500 ease-in-out hover:bg-algae hover:text-white ${lausanne.className}`}>
              Menu <HiMiniArrowUpRight size={20} strokeWidth={1} />
            </button>
          </h1>
          <div className="hidden md:flex">
            <motion.div
              initial={{ rotate: 0, x: 30, y: -50 }}
              animate={{ rotate: -30, x: [30, -5, 0], y: [-50, -5, 0] }}
              transition={{ duration: 1.5 }}
              whileHover={{ scale: 1.05, transition: { duration: 0.3 } }}
            >
              <Image
                src={gobhiPic}
                height={850}
                width={850}
                alt="Hero image"
                priority={true}
                className="drop-shadow-xl md:drop-shadow-2xl"
              />
            </motion.div>
          </div>
        </div>
      </motion.div>
    </div>
  );
};

export default Hero;

This all works fine but now I am adding another component beneath Hero which should ideally be visible after scrolling.

About.js

import Juana from 'next/font/local';

const juana = Juana({ src: '../assets/Juana-Medium.otf' })

const About = () => {
  return (
    <div className={`flex w-full items-center bg-black`}>
      <div className={`flex text-black-ribbon justify-center`}>
          <h1 className={`text-4xl ${juana.className}`}>About</h1>
      </div>
    </div>
  );
};

export default About;

The problem is, NextJS renders the About component not beneath the Hero but within the screen view. I added a bg-black class to debug this and you can see in the screenshot that the component shows up inside the screen height instead of beneath the Hero component. If I remove min-h-screen from the main tag the About component just disappears. What I want to do is render the Hero component on the entire screen then scroll down to About.

This is my first project with NextJS and Tailwind so apologies if this is something super trivial. Thanks in advance!

Edit: I know the button tag is incorrect and it should be the a> tag forgot to fix it before posting sorry!

Screenshot of the problem

How do I check the value inside an HTML element and use it in an if statement

So, I am trying to check the value inside an HTML element and use it as a conditional in an if statement in Javascript/TypeScript.

I am trying to do the following: if the element contains “-“, you can stop playing, else, click the button and proceed with the game.

I initially created a variable where I could store the element

 const gameButton: string = '#GameButton';

Then I created an if statement where I used gameButton inside the conditional:

if (gameButton.includes("-") {
 console.log("Stop the game")
} else {
console.log("Click button to continue")
}

What is happening is that regardless of the value inside the button, I am still getting the “Click button to continue” message on console each time. What is the correct way of doing this?

what is write way to learn a JavaScript ? for a fresher

what is a better learning way JavaScript to develop a good projects and more knowledge ? am a fresher and now join this community have no idea how can use this community can only tray bur have more curious about learn new technology and tools so can search how can am learn new things in a better way so give me answer my question….!