Calling async functions without await [duplicate]

I have an async function that returns a promise.

A:

const promise = async (): Promise<string> => {
  return new Promise((res, rej) => {
    if (true) {
      res("success");
    } else rej("rejected");
  });
};

B:

const caller = async () => {
  try {
    const res = await promise();
    console.log(res);
  } catch (err) {
    console.log(err);
  }
};

C:

caller();

Results:

[nodemon] starting `ts-node j.ts`
success
[nodemon] clean exit - waiting for changes before restart

Why is it that I need to declare caller as async in (B) because the promise is declared as async in (A). Yet when I call the caller() in (C), I don’t need to await the async function ?

Thanks.

Firebase updateDoc function not working Reactjs

I’m trying to update my document on firestore, i’m able to get the data and prefill it in the placholder but i’m having issues with updating the data with updateDoc.

I have tried to print out the values and it is still the same data and nothing changes within the code. My firebase version is 10.7.2.

 
 function EditTodo({ setTodo, todo }) {
   const [show, setShow] = useState(false);
    const [date, setDate] = useState("");
 
   const handleClose = () => setShow(false);
   const handleShow = () => setShow(true);

   const handleUpdate = async () => {
     //   e.preventDefault()
     const docRef = doc(db, "todos",todo.id);
     try {
       await updateDoc(docRef, {
         todo: todo.todo,
         date: todo.date,
       });

       window.location.reload();
     } catch (err) {
       alert(err);
     }
   };

   return (
     <>
       <i
         className="fa fa-pencil fa-1x rounded-circle border  border-primary p-2"
         aria-hidden="true"
         onClick={handleShow}
       ></i>

       <Modal show={show} onHide={handleClose}>
         <Modal.Header closeButton>
           <Modal.Title>Todo Name: {todo.todo}</Modal.Title>
         </Modal.Header>
         <Modal.Body>
           <Form.Label>Todo</Form.Label>
           <Form.Control
             required
             type="text"
             className="input"
             placeholder={todo.id}
           />
           <Form.Control
             required
             type="text"
             className="input"
             placeholder={todo.todo}
             onChange={(e) => setTodo(e.target.value)}
           />
           <Form.Control
             required
             type="date"
             className="input my-2"
             placeholder={todo.date}
             onChange={(e) => setDate(e.target.value)}
           />
         </Modal.Body>
         <Modal.Footer>
           <Button variant="secondary" onClick={handleClose}>
             Close
           </Button>
           <Button variant="primary" onClick={handleUpdate}>
             Save Changes
           </Button>
         </Modal.Footer>
       </Modal>
     </>
   );
 }

export default EditTodo;

Should object properties be created inside of methods?

Doing some JavaScript review and learned that it is possible to create a new property inside of an object’s method. Is this considered a clean way of adding a property?

const car = {
    manufactureYear: 2012,
    calcAge: function () {
        // Creating a new property for car
        this.age = 2024 - this.manufactureYear;
        return this.age;
    }
};

console.log(car.calcAge());
console.log(car.age);

I would think it would be better to extract the property creation outside of the method like so:

const car = {
    manufactureYear: 2012,
    calcAge: function () {
        return 2024 - this.manufactureYear;
    }
};

car.age = car.calcAge()
console.log(car.age)

I believe both methods are viable. It is less code the first way, but I like the visibility of the property creation on the second method.

why do i get error of Cannot read properties of undefined (reading ‘value’) from NextOptionsContext.js from clerk pkg i am using @clerk/next 4.2.6v

Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading ‘value’)

Call Stack
value
node_modules@clerknextjsdistesmclient-boundaryNextOptionsContext.js (6:13)
useClerkNextOptions
[email protected] (18:63)
Component
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (11021:17)
renderWithHooks
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (16184:19)
updateFunctionComponent
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (16667:16)
mountLazyComponent
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (18388:15)
beginWork$1
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (26791:13)
beginWork
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (25637:11)
performUnitOfWork
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (25353:4)
workLoopSync
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (25308:6)
renderRootSync
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (24525:19)
recoverFromConcurrentError
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (24470:25)
callback
node_modulesnextdistcompiledschedulercjsscheduler.development.js (256:33)
workLoop
node_modulesnextdistcompiledschedulercjsscheduler.development.js (225:13)
flushWork
node_modulesnextdistcompiledschedulercjsscheduler.development.js (534:20)

I tried changing version but then i get errrors about middleware

How to get value of escape sequences inside HTML textarea

I have a textarea, and inside of it, I would like to be able to input text alongside escape sequences.

For example, lets say that inside the textarea is:

HellonWorld.

Now, If I wanted to print that value to the console by using:

console.log( document.getElementById('myTextArea').value )

The output that I would like would be:

Hello
World

But instead, it outputs:

HellonWorld

This makes since, because that’s what I put in. But I would like to convert these sequences to their actual values

Now I’m sure this is possible with a simple string replace, like:

str.replaceAll('\n', 'n')

But I would like to be able to do this with ANY escape sequence. like:
u0000, r, u0020

So is it possible to extract these sequences from a textarea?

How to create a channel in discord.js v14

I can’t seem to create a channel none of the code I find ever works somebody please tell me how

client.on('messageCreate', async (msg) => { 
  if (msg.content === '$setup') {
      msg.reply('Setup command received');

      msg.guild.channels.create({
          name: "new-channel",
          type: "text",
          permissionOverwrites: [
              {
                  id: msg.guild.id,
                  accept: [PermissionsBitField.Flags.ViewChannel],
              },
          ],
      });
  }

I expected this to create the channel but it just gives:

/home/runner/MegaBot/node_modules/@discordjs/rest/dist/index.js:722
      throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
            ^

DiscordAPIError[50035]: Invalid Form Body
type[NUMBER_TYPE_COERCE]: Value "text" is not int32.
    at handleErrors (/home/runner/MegaBot/node_modules/@discordjs/rest/dist/index.js:722:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.runRequest (/home/runner/MegaBot/node_modules/@discordjs/rest/dist/index.js:1120:23)
    at async SequentialHandler.queueRequest (/home/runner/MegaBot/node_modules/@discordjs/rest/dist/index.js:953:14)
    at async _REST.request (/home/runner/MegaBot/node_modules/@discordjs/rest/dist/index.js:1266:22)
    at async GuildChannelManager.create (/home/runner/MegaBot/node_modules/discord.js/src/managers/GuildChannelManager.js:171:18) {
  requestBody: {
    files: undefined,
    json: {
      name: 'new-channel',
      topic: undefined,
      type: 'text',
      nsfw: undefined,
      bitrate: undefined,
      user_limit: undefined,
      parent_id: undefined,
      position: undefined,
      permission_overwrites: [ { id: '1157099244453376162', type: 0, allow: '0', deny: '0' } ],
      rate_limit_per_user: undefined,
      rtc_region: undefined,
      video_quality_mode: undefined,
      default_thread_rate_limit_per_user: undefined,
      available_tags: undefined,
      default_reaction_emoji: undefined,
      default_auto_archive_duration: undefined,
      default_sort_order: undefined,
      default_forum_layout: undefined
    }
  },
  rawError: {
    message: 'Invalid Form Body',
    code: 50035,
    errors: {
      type: {
        _errors: [
          {
            code: 'NUMBER_TYPE_COERCE',
            message: 'Value "text" is not int32.'
          }
        ]
      }
    }
  },
  code: 50035,
  status: 400,
  method: 'POST',
  url: 'https://discord.com/api/v10/guilds/1157099244453376162/channels'
}

Node.js v20.10.0

I am using discord.js v14.14.1 and I have searched basically everywhere and cannot find a solution.

upload image using flask and ajx (alwys empty form data)

i am new in Flask and try to upload images using ajax and form data and I always get form data sent as empty filed and my function always gets stuck in a validation error as filed is required even i click and send the image inside form,i need some one to help me to solve this issue.i see more solution and dint got the issue.

my code here

@presentation.route('/presentation/updateImage',methods=['POST'])
@login_required
def updateImage() :

    UpdateImageForm = UpdateImage(request.form)
    if  UpdateImageForm.validate_on_submit() :
        
        image        = request.json.get("image")
        print(image)
        return jsonify({'status': "success", 'message': 'Password Changed Successfuly','id':image})               
    else:   
        errors = {}
        for field, field_errors in UpdateImageForm.errors.items():
            errors[field] = [str(error) for error in field_errors]
        return jsonify({'status': "errors ", 'message': errors})   

my form is :

                    <div class="modal fade" id="update-img" tabindex="-1" aria-hidden="true">
                      <div class="modal-dialog modal-dialog-centered1 modal-simple modal-add-new-cc">
                        <div class="modal-content p-3 p-md-5">
                          <div class="modal-body">
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            <div class="text-center mb-4">
                              <h3 class="mb-2">Change Image</h3>
                           
                            </div>
                            <form id="updateImage"  method="POST" class="row g-3" enctype="multipart/form-data">
                                {{UpdateImageForm.hidden_tag()}}
                              <label class="form-label" for="bs-validation-upload-file">Presntaion  Images</label>
                              <div class="mb-3">
                                {{ UpdateImageForm.image(class_="form-control") }}<br>

                              </div>

               
                            
                              <div class="col-12 text-center">
                                <button type="submit" class="btn btn-primary me-sm-3 me-1">Submit</button>
                                <button
                                  type="reset"
                                  class="btn btn-label-secondary btn-reset"
                                  data-bs-dismiss="modal"
                                  aria-label="Close">
                                  Cancel
                                </button>
                              </div>
                            </form>
                          </div>
                        </div>
                      </div>
                    </div>

js code :

  // start edit image
  $(".table_for_data").on( 'click', '.editImage', function () {
    $("#updateImageResult").html("");
    // get id for update
    var myId = $(this).attr("data-id");
   // alert(myId)
    $("#updateImage").submit(function(e){
      e.preventDefault()
    var form_data = new FormData($('#updateImage')[0]);
        $.ajax({
          url: "{{ url_for('presentation.updateImage') }} ",
            type: "POST",
            data: JSON.stringify(form_data),                
            contentType: 'application/json',                 
            beforeSend:function(){
                $(".loadingImage").show();
            },
            statusCode: {
                404: function() {
                    alert( "page not found" );
                },
            },
            success:function(valdata) {
              alert('success')
             
            }
        });
        return false;
    });
});

i’m trying to mask the text with a video background but it isnt working as expected

This video shows what i want the result to be: https://youtu.be/n_9UKMDEYg0
when i try to make this animation it doesn’t work

i tried using mix-blend-mode and tried using a transparent background.

my goal is to have the background and text the same colors as in the video, then the text becomes transparent revealing the video .

<div className="video-background">
    <video src={Video} autoPlay loop muted />
    <div></div>
    <img src={GPSI} alt="background" />
    <span>GPSI</span>
</div>
body {
  overflow: hidden
}

.video-background {
  width: 100%;
  height: 100%;
  overflow: hidden
}

.video-background > video {
  width: 100vw;
  height: 100vh;
  object-fit: cover;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: -1;
}

.video-background > img {
  width: 100vw;
  height: 100vh;
  object-fit: cover;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;

  /* animation: scale 6s forwards 1s; */
}

.video-background > div {
  width: 100vw;
  height: 100vh;
  /* opacity: 0%; */
  background-color: #1A1A1A;
  /* animation: fade 3s forwards; */
}

.video-background > div {
  position: absolute;
  top: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background: #fff;
  color: #fff;
  mix-blend-mode: multiply;
  animation: to-white 3.5s forwards, blend 3.5s forwards, scale 4s forwards 4s;
} 


.video-background > span {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  top: -6%;
  left: 0%;
  font-size: 37vw;
  font-weight: 700;
  user-select: none;
  color: #fff;
  letter-spacing: 0.75rem;

  /* animation: slide-in 2s forwards 500ms;
  transform: translateY(-150%); */
}
}

@keyframes scale {
  0% {
    transform: scale(1);
  }
  100% {
    transform: scale(250);
    display: none;
  }
}

@keyframes slide-in {
  0% {
    transform: translateY(-100%);
  }

  70% {
    transform: translateY(0%);
  }

  100% {
    transform: translateY(0%);
  }
}

@keyframes to-white {
  0% {
    color: #141414;
    background-color: #1a1a1a;
  }

  75% {
    color: #141414;
    background-color: #1a1a1a;
  }

  76% {
    background-color: #000;
  }

  100% {
    color: #fff;
    background-color: #000;
  }
}

@keyframes fade {
  0% {
    opacity: 100%;
  }

  70% {
    opacity: 100%;
  }

  100% {
    opacity: 0%;
  }
}

Carousel doesn’t show 2 slides per view

I am creating a carousel from scratch using React.

'use client'
import React, { useEffect, useRef, useState } from 'react'
import './Carousel.css' 
import Image from 'next/image'
import clsx from 'clsx'

const Carousel = ({ images }) => {
  const [currentSlide, setCurrentSlide] = useState(0)
  const carouselRef = useRef(null)

  const handleBulletClick = index => {
    setCurrentSlide(index)
    scrollToSlide(index)
  }

  const scrollToSlide = slideIndex => {
    const slideWidth = carouselRef.current.clientWidth
    carouselRef.current.scrollTo({
      left: slideWidth * slideIndex,
      behavior: 'smooth'
    })
  }

  return (
    <div className="relative">
      <div className="lg:block hidden absolute -bottom-8 left-1/2 -translate-x-1/2 h-5 w-full">
        <div className="flex gap-2 justify-center mt-2">
          {Array.from({ length: Math.ceil(images.length / 2) }, (_, index) => (
            <button
              key={index}
              className={clsx('carousel-bullet', index === currentSlide && 'active')}
              onClick={() => handleBulletClick(index)}
            />
          ))}
        </div>
      </div>
      <div className="my-4">
        <div className="carousel-video " ref={carouselRef}>
          {images.map((image, index) => (
            <div className="carousel--slide" key={index}>
              <article className="w-full h-full flex items-center flex-col">
                <Image src={image} alt={image.alt} width={1440} height={500} />
                <h4 className="text-sm opacity-70 pt-2">{image.alt}</h4>
              </article>
            </div>
          ))}
        </div>

      </div>
    </div>
  )
}

export default Carousel

this is my css:

:root {
  --carousel-gap: 1rem;
  --slides-per-view-video: 2;
}
.carousel-video {
  scroll-snap-type: none;
  display: flex;
  align-items: flex-start;
  gap: var(--carousel-gap, 0);
  --slide-size: calc(
    calc((100% + var(--carousel-gap)) / var(--slides-per-view-video)) - var(--carousel-gap)
  );
  overflow-x: scroll;
  scroll-behavior: smooth;
  scroll-snap-type: x mandatory;
  -ms-overflow-style: none;
  scrollbar-width: none;
  align-items: stretch !important;
}
.carousel--slide {
  flex: 0 0 var(--slide-size);
  scroll-snap-align: center;
  transform: translateZ(0);
  position: relative;
}
.carousel-bullet {
  width: 16px;
  height: 4px;
  background-color: #ccc;
  border-radius: 20%;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.carousel-bullet.active {
  background-color: #333;
}

This Carousel does work and paginate as it should, when having even numbers carousel slides (2,4,6… ) and i try to paginate it shows 2 slides per view. But unfortunately when there are odd number of slides (3,5,7… ) when paginating, it won’t show 2 slides per view, how can I fix this?

This is a demo:
https://stackblitz.com/edit/stackblitz-starters-u13jbf

how can i know the total number of characters that have been typed into a textarea (including characters that have been deleted)

I am very new to programming so please forgive me if this has a very simple solution. My problem is that i cannot figure out how i can calculate the number of characters that have been typed in the textarea in total (not just at that time). I have used the .value to calculate how many characters have been typed in the textarea at that time. But i want to know the number of characters that have been typed since the program has been running as well. Below is my code which i have shortened for simplicity. I have tried if statements that add +2 if you delete a character. However, i cant get this to work properly.

let textToType = document.getElementById("text-to-type");
let textBox = document.getElementsByClassName("text-box")[0];
// !typedValue shows you how many characters you have typed into the textarea
let typedValue;
let displayText = "Sample text to type"; // This text will add to text-to-type div
// ! displayTextLength is how many characters long the displayText is
let displayTextLength = displayText.length;
let getTextSpan = textToType.getElementsByTagName("span");
let stopwatch = 0;
let popUpReminder = document.getElementsByClassName("reminder")[0];
popUpReminder.style.display = "none";


window.onload = () => {
    for (let i in displayText) {
        const spanTag = document.createElement("span");
        const textNode = document.createTextNode(displayText[i]);
        spanTag.appendChild(textNode);
        textToType.appendChild(spanTag);
    }
};

setInterval(function () {
    stopwatch++;
}, 1000);

const run = () => {
    typedValue = textBox.value;
    let isCorrect = true;

    for (let i in displayText) {
        // This nested loop will prevent red colour to show on the text that isn't  typed yet
        console.log(typedValue.length);
        for (let j in typedValue) {
            if (typedValue.length <= displayText.length) {
                if (typedValue[j] !== displayText[j]) {
                    getTextSpan[j].style.color = "red";
                }
            }
        }

        if (typedValue[i] === displayText[i]) {
            getTextSpan[i].style.color = "#579984";
        } else {
            // Black color for those characters that didn't typed yet.
            getTextSpan[i].style.color = "black";
        }

        // reminder
        let typedValueLength = typedValue.length;
        if (typedValueLength > displayTextLength) {
            console.log("To complete the typing test you must complete type the text displayed without any typos.");
            popUpReminder.style.display = "block";
        }
    }

    // Makes it so that you need to type whats displayed to complete the typing test.
    if (typedValue === displayText) {
        console.log("TYPING COMPLETE");
        console.log("It took you " + stopwatch + " seconds to complete.");
    }
};
<textarea class="text-box" rows="8" cols="55" oninput="run()"></textarea>

Trying to create a published browser based npm package, but import isn’t working

I am using webpack to create and bundle up a package. I’ve then published it to NPM. Then in a test environment I install the package but using import/export doesn’t work:
This is the webpack file for the package I uploaded.

/* webpack.config.js
const path = require('path');

module.exports = {
    entry: './src/index.js',
  target: 'web',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
        library: 'myWebpackPackage',
        libraryTarget: 'umd',
    },
}; 

The simple function I created in the index.js:

export function add(a, b) {
return a + b;
}

The package.json file:

{
  "name": "my-first-npm-package-twelve",
  "version": "1.0.6",
  "description": "",
  "main": "./dist/bundle.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "build": "webpack"
  },
  "keywords": [],
  "author": "Me",
  "license": "MIT",
  "devDependencies": {
    "cli": "^1.0.1",
    "webpack": "^5.90.1",
    "webpack-cli": "^5.1.4"
  }
}

I successfuly publish to the NPM repository.
However when I come to importing it into my test environment it only works if I specifically label the path:
index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script type="module" src="./node_modules/my-first-npm-package-twelve/dist/bundle.js"></script>
  <script  type="module" src="index.js"></script>
</body>
</html>

Index.js:

console.log(myWebpackPackage.add(5,6));

Which prints the answer 11 in the browser javascript console:
enter image description here

Please let me know what I am doing wrong, I’ve been struggling with this for the passed week.

I expected that by placing an import statement in the index.js that I could call the function from. the downloaded package.

Automatically Remove word line from blockquote after click button in JavaScript how to keep original formatting of the text

I’m working on a JavaScript project where I have a blockquote containing multiple lines of text. I need to create a functionality where, upon clicking a button, specific words are automatically removed from each line of the blockquote, while preserving the original formatting of the text.

  const highlightWordsArray = [
  'word1',
  'word2',
  'word3',
  'word4',
  // Add more words here
];

 document.addEventListener('DOMContentLoaded', function () {
    const blockquote = document.querySelector('blockquote');
    const highlightButton = document.getElementById('highlightButton');

    highlightButton.addEventListener('click', function () {
      highlightWordsInBlockquote();
    });

    function highlightWordsInBlockquote() {
      const lines = blockquote.textContent.trim().split('n');
      const highlightedLines = lines.map(line => {
        const words = line.split(/s+/);
        const highlightedWords = words.map(word => {
          return !highlightWordsArray.includes(word) ? `<span class="highlight">${word}</span>` : word;
        }).join(' ');
        return highlightedWords;
      });

      blockquote.innerHTML = highlightedLines.join('<br>');
    }

    // Move overflow words to the next line
    function moveOverflowWordsToNextLine() {
      const blockquote = document.querySelector('blockquote');
      const blockquoteHeight = blockquote.clientHeight;
      const blockquoteScrollHeight = blockquote.scrollHeight;
      
      if (blockquoteScrollHeight > blockquoteHeight) {
        blockquote.innerHTML = blockquote.innerHTML.replace(/ /g, '&nbsp;');
      }
    }

    // Call the function initially and on window resize
    moveOverflowWordsToNextLine();
    window.addEventListener('resize', moveOverflowWordsToNextLine);
  });
 blockquote {
      border-left: 4px solid #3498db;
      
      font-size: 18px;
      font-style: italic;
      
      background: linear-gradient(white, white) padding-box, url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/80625/sea.jpg) border-box 0 / cover;
      border: 2em solid transparent;
      box-shadow: 2px 3px 30px black;
      height: 500px;
      width: 1140px;
      overflow-y: scroll;
      
    }


    button {
      padding: 10px;
      background-color: #3498db;
      color: #fff;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }



    .highlight {
      background-color: yellow; /* You can customize the highlight style */
      cursor: pointer;
    }
<!DOCTYPE html>
<html lang="en">
<head>
  <script src="https://code.jquery.com/jquery-git.js"></script>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>rebaz</title>

 
</head>

<body class="card">
  <blockquote contenteditable="true" spellcheck="false">
    <p>Start typing here...</p>
  </blockquote>

  <button id="highlightButton">Highlight Words</button>

  <ul class="custom-context-menu">
    <!-- Options will be dynamically added here -->
  </ul>

  
  <div class="backdrop"></div>


</body>
</html>

I want to create a JavaScript function that, upon clicking a button, removes these words from each line of the blockquote while keeping the original formatting intact. This means that the line breaks and paragraph structure should be preserved.

I’ve tried using the split and join methods along with regular expressions, but I’m having trouble maintaining the original formatting of the text.

Trying to find a way to boost scraping student’s colleagues information but it takes so much time since there are a lot of scrolling

I was trying to loop through each course of a student on a platform and get all his colleagues’ names but there is a possibility that there are some names that are not loaded so I had to find a way to scroll down so I created this approach below:

async function getClassmates(page) {
    const buttonSelector = 'p[bb-translate]';
    const rosterSelector = '#rosterView-list';

    // Click on the button
    const button = await page.waitForSelector(buttonSelector);
    await button.click();

    // Wait for the roster selector to appear
    await page.waitForSelector(rosterSelector);

    // Add a delay if needed before going back
    await page.waitForTimeout(2000);
    await saveRoster(page);
    // Go back
    // button[class="bb-close"][data-close="bb-offcanvas"]
    const goBackOption = await page.waitForSelector('#main-content > div.bb-offcanvas-panel.bb-offcanvas-right.full.hide-in-background.panel-has-focus.active > div > button[class="bb-close"][data-close="bb-offcanvas"]');

    await page.waitForTimeout(2000);
    await goBackOption.click();

    // Add another delay if needed after going back
    await page.waitForTimeout(2000);
}

async function saveRoster(page) {
    const allRoster = '#rosterView-list > ul > li.js-roster-members-list-item bdi';
    // const colleagues = await page.$$(allRoster);

    // I just wanna make sure that the rest of the roster data is loaded
    let previousCount = 0;
    let currentCount = 0;
    do {
        // Update the count of elements
        previousCount = currentCount;

        // Scroll to the end of the list
        await page.evaluate(() => {
            const lastLi = document.querySelector('#rosterView-list > ul > li:last-child');
            lastLi.scrollIntoView();
        });

        // Wait for a short duration to let new elements load
        await page.waitForTimeout(4000);

        // Get the current count of elements
        const elements = await page.$$(allRoster);
        currentCount = elements.length;

        await page.waitForTimeout(4000);
    } while (currentCount > previousCount);
    console.log('Counter is ', currentCount);
    // Create a JavaScript object to store the count of names for each header
    const countOfNames = {};

    // Get the current header from the page
    const headerText = await page.evaluate(() => {
        const header = document.querySelector('h1.js-readonly-header-text');
        return header ? header.innerText : '';
    });

    // If the header exists, initialize its entry in countOfNames
    if (headerText) {
        countOfNames[headerText] = {};
    }
    const RenewiedColleague = await page.$$(allRoster);
    // Collect the innerText of each element into a list
    const filePath = './Database/coursesData.json';

    try {
        // Read existing data from the file
        let existingData = await fs.readFile(filePath, 'utf-8');
        existingData = JSON.parse(existingData);

        // Get the current header from the page
        const headerText = await page.evaluate(() => {
            const header = document.querySelector('h1.js-readonly-header-text');
            return header ? header.innerText : '';
        });

        // If the header exists in the JSON file, update it
        const existingEntryIndex = existingData.findIndex(entry => entry.header === headerText);

        if (existingEntryIndex !== -1) {
            // Collect the innerText of each element into a list
            const namesList = [];
            for (let index = 0; index < currentCount; index++) {
                if (index >= 0 && index < currentCount) {
                    const colleagueText = await page.evaluate(colleague => colleague.innerText, RenewiedColleague[index]);
                    namesList.push(colleagueText);
                } else {
                    console.error('Invalid index for getting roster.');
                }
            }

   
            const numberOfNames = currentCount;

            existingData[existingEntryIndex].names = namesList;
            existingData[existingEntryIndex].otherNames = numberOfNames;

            await fs.writeFile(filePath, JSON.stringify(existingData), 'utf-8');
            console.log('File updated with names and numberOfNames data.');
        } else {
            console.error('Header not found in the JSON file.');
        }

    } catch (error) {
        console.error('Error reading or updating the JSON file:', error);
    }

    console.log(countOfNames);

}

as you can see in here :

let previousCount = 0;
    let currentCount = 0;
    do {
        // Update the count of elements
        previousCount = currentCount;

        // Scroll to the end of the list
        await page.evaluate(() => {
            const lastLi = document.querySelector('#rosterView-list > ul > li:last-child');
            lastLi.scrollIntoView();
        });

        // Wait for a short duration to let new elements load
        await page.waitForTimeout(4000);

        // Get the current count of elements
        const elements = await page.$$(allRoster);
        currentCount = elements.length;

        await page.waitForTimeout(4000);
    } while (currentCount > previousCount);

I created two counters . I am just basically scrolling down so that I assure that all the names are loaded. My problem is that this process takes so much time and I tried to decrease the timeout but there are so many names to load that the headless browser will hang up. In general, this process takes much time like 40 minutes. I hope someone helps me find a way to make it faster to be 5 minutes or so.

I expecting to find another approach to boost the speed of getting all students efficiently.

Create firestore document without instant database write

Is it possible to create a firestore document without instantly writing to the db?

I want to do something like this:

const documentReference = await addDoc(..., { write: false });
// Run operations
await updateDoc(documentReference, { data: operationResult });
// ...
await applyToDatabase(documentReference);

The { write: false } parameter and applyToDatabase function are imaginary functionality that I want to know if there is an equivalent of.

Layout with cards from Figma design using REACT , html and css

I am new to programming and I encountered a problem which i cannot solve.

Design: Link to design

the problem is that i cannot come up with idea how to make this View More feature to appear under the Row on which the card is clicked. Ive made similar with modals or redirect to new page, but i dont know how to make it render to look like the figma design above.

Can anyone help 🙂 Thank you! 🙂

first i though to push each movie html into an array and after every 3rd movie to insert a row with the additional data, but that wont work when i try to make the design responsive. As seen in the mobile version.

Even a hint will be enough, since i want to try and write it myself. 🙂 Thank you

For more info this is what i am talking about:

cut out image of the more info dialog window