How do I prevent the div.tooltip-inner from disappearing when the mouse is over it in a tooltip created using Bootstrap v5.3.2?

HTML

<aside class="sidebar" id="sidebar">
<ul class="sidebar_content">
<li data-bs-toggle="tooltip" data-bs-placement="right" aria-label="Item-1" data-bs-html="true"                                                                    data-bs-original-title="<a href='#'>Item-1</a>">
</ul>
</aside>

JS

hamBurger.addEventListener("click", function () {
    const sidebar = document.querySelector("#sidebar");
    sidebar.classList.toggle("minimize");
    const isMinimized = sidebar.classList.contains("minimize");
    if (isMinimized) {
        enableTooltips(); 
    } else {
        disableTooltips();
    }
});

function enableTooltips() {
    const tooltipTriggerListInSidebar = document.querySelectorAll('#sidebar.minimize li[data-bs-toggle="tooltip"]');
    tooltipTriggerListInSidebar.forEach(function(tooltipTriggerEl) {
        new bootstrap.Tooltip(tooltipTriggerEl, {
            delay: {
                "show": 0,
                "hide": 250
            }
        });
    });
}

function disableTooltips() {
    const tooltipTriggerListInSidebar = document.querySelectorAll('#sidebar li[data-bs-toggle="tooltip"]');
    tooltipTriggerListInSidebar.forEach(function(tooltipTriggerEl) {
        const tooltipInstance = bootstrap.Tooltip.getInstance(tooltipTriggerEl);
        if (tooltipInstance) {
            tooltipInstance.disable();
        }
    });
}

enter image description here

I want to prevent the div.tooltip-inner from closing 250ms after the mouse is over it. Additionally, the div should disappear when the mouse leaves the tooltip-inner.

It seems like you’re having trouble preventing the closure of the div.tooltip-inner when the mouse is over it. Even with the specified delay of 250ms for the hide action, the tooltip still disappears.

npm run build ignores some files and doesnt create them

Im working on a vanilla js project, i just tried doing npm run build, turns out it completely ignores half of the files in the folder. This is the picture of the files: (https://i.stack.imgur.com/d06dK.png) This is the build that i get after .

This is the package.json file: (https://i.stack.imgur.com/fZtyc.png)

I wanted to publish the site to Netlify, site is 100% fine locally, i can open a live server of it and it works fine. But if i do npm start or npm run build, i cant go to the login page since the file is ignored.

2 or 3 days ago the files worked fine but now they stopped being processed for whatever reason.

I tried doing npm run build and npx serve -s dist, but all i got is exactly what i expected, i got a message from the build command telling me the site was successfuly built, but when i check which files were built, it didnt show the login page, and some other files too. After opening the site from npx serve Locally, login didnt work again.

A “scoping” clash when tracking completed requires input fields on each form

The problem that I am experiencing is that if there are more than one form “.kn-form” then if the first form contains at least one required field that is not completed “function updateFormCompletion(thisFormViewFormRequiredSelector) {” then the second form is afflicted and has its class “allRequiredCompleted” removed as well, indicating that other forms beyond the first from being tethered to the first form. Even if the second form has all of its required fields completed it will not embrace the class “allRequiredCompleted”, only when the first form has “allRequiredCompleted” then the second form will enact “allRequiredCompleted”. However, even if the second form does not have all of its required fields completed then it still gains “allRequiredCompleted” because the first form has all of its required fields completed.

I believe the issue has something to do with “scoping” but I do not know how to get around this.

function updateFormCompletion($form) {


    // Use the $form parameter to scope our selectors to the current form
    if ($form.find('.kn-input-required.completed').length === $form.find('.kn-input-required:not([style="display: none;"])').length) {
        $form.find('.kn-submit').show();
        $form.addClass('allRequiredCompleted');
    } else {
        $form.find('.kn-submit').hide();
        $form.removeClass('allRequiredCompleted');
    }
}


$(document).ready(function() {

    $('[id^="view_"]').each(function() {
        var fullViewId = $(this).attr('id');
        var viewNumber = fullViewId.split('_')[1];

        

                var $form = $(this);

        $form.find('.kn-input').each(function() {
            if ($(this).find('span.kn-required').length > 0) {

$(this).addClass('kn-input-required');


$form.addClass('kn-form-required');
            }
        });



$form.find('.kn-input-required input').on('input blur change', handleInputChange);


$form.find('.kn-input-required input').each(handleInputChange);
    });

});


  function handleInputChange() {
    var $input = $(this);
    var $parent = $input.closest('.kn-input-required');
        var $form = $input.closest('.kn-form-required'); // Scope to the current form

      if ($input.val().trim() !== '' || $input.text().trim() !== '') {
        $parent.addClass('completed');
      } else {
        $parent.removeClass('completed');
      }
    
    
    updateFormCompletion($form);

  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>


<div class="view-column view-column-group-1">
  <div class="kn-form kn-view view_6188" id="view_6188">
    <div class="view-header">
      <h2 class="kn-title">Add ACCOUNT</h2>
    </div>
    <div class="kn-form-confirmation" style="display: none">
      <div class="kn-message success">
        <p></p>
      </div>
      <a href="#" class="kn-form-reload button">
        <span class="icon is-small">
          <i class="fa fa-refresh"></i>
        </span>
        <span>Reload form</span>
      </a>
    </div>
    <form action="#" method="post" novalidate="">
      <ul class="kn-form-group columns kn-form-group-1 kn-form-group-number-1 parent-halves">
        <li class="kn-form-col column is-constrained first-half">
          <div class="kn-input kn-input-short_text control" id="kn-input-field_6831" data-input-id="field_6831">
            <label for="field_6831" class="label kn-label">
              <span>Service Element Title</span>
              <span class="kn-required">*</span>
            </label>
            <p class="kn-instructions" style="display: none;"></p>
            <div class="control">
              <input class="input" id="field_6831" name="field_6831" type="text" value="" placeholder="Enter Details Here">
            </div>
          </div>
        </li>
      </ul>
      <div class="kn-submit" style="display: block;">
        <input name="view_key" type="hidden" value="view_6188">
        <input name="view_name" type="hidden" value="Add ACCOUNT">
        <button class="kn-button is-primary" type="submit"> Submit </button>
      </div>
    </form>
  </div>
  <div class="kn-form kn-view view_6188" id="view_6188">
    <div class="view-header">
      <h2 class="kn-title">Add ACCOUNT</h2>
    </div>
    <div class="kn-form-confirmation" style="display: none">
      <div class="kn-message success">
        <p></p>
      </div>
      <a href="#" class="kn-form-reload button">
        <span class="icon is-small">
          <i class="fa fa-refresh"></i>
        </span>
        <span>Reload form</span>
      </a>
    </div>
    <form action="#" method="post" novalidate="">
      <ul class="kn-form-group columns kn-form-group-1 kn-form-group-number-1 parent-halves">
        <li class="kn-form-col column is-constrained first-half">
          <div class="kn-input kn-input-short_text control" id="kn-input-field_6831" data-input-id="field_6831">
            <label for="field_6831" class="label kn-label">
              <span>Service Element Title</span>
              <span class="kn-required">*</span>
            </label>
            <p class="kn-instructions" style="display: none;"></p>
            <div class="control">
              <input class="input" id="field_6831" name="field_6831" type="text" value="" placeholder="Enter Details Here">
            </div>
          </div>
        </li>
      </ul>
      <div class="kn-submit" style="display: block;">
        <input name="view_key" type="hidden" value="view_6188">
        <input name="view_name" type="hidden" value="Add ACCOUNT">
        <button class="kn-button is-primary" type="submit"> Submit </button>
      </div>
    </form>
  </div>
</div>

Issue with filtering data from instances

I am having an issue finding the right answer for this.

I have an instance of TobaccoModel and example is provided below.

  new TobaccoModel(264, "dleaf", "Example", "Banana", "fruity", "Example description #1", "low"),
  new TobaccoModel(265, "dleaf", "Example #2", "Berry", "berry-ice", "Example description #2", "low"),
  new TobaccoModel(266, "dleaf", "Example #3", "Cola", "fruity-spice", "Example description #3", "low")

And I have the below function (part of it)

const genMix = () => {
        let filteredData = BrandFlavorData.filter((item) => {
                  let meetsTypeCriteria = type.some(element => item.flavorTypeCategory.includes(element) && !item.flavorTypeCategory.includes(type.join('-')))
    return meetsTypeCriteria
}

The issue that I am having is when for example an user chooses a type of “fruity” the meetTypeCriteria pulls “fruity” and also “fruity-spice” and I want to make sure that it only pulls what the user chose.

Below is also my useState that I have for the “type”

const [type, setType] = React.useState([]);

Here is also my class for the TobaccoModel

class TobaccoModel {
    constructor(id, category, brandName, flavor, flavorTypeCategory, description, nicotine) {
      this.id = id,
      this.category = category,
      this.brandName = brandName,
      this.flavor = flavor,
      this.flavorTypeCategory = flavorTypeCategory,
      this.description = description
      this.nicotine = nicotine
    }
}

export default TobaccoModel;

What can I do to fix this?

Test emails flows with Playwright and Mailosaur

I’m writhing test for Forgot password flow in Playwright JS and for that purpose I’m using Mailosaur. Problem I have is when I run same test few times, my Mailosaur inbox won’t refresh and test doesn’t won’t to pick up last email in inbox. It’s always picks previous email in inbox and every second test is failing because it clicks on expire link. Is there any way I can refresh Mailosaur inbox or delete email after test is done to overcome this issue. I’m always using same email address.

This is the code for clicking reset password link:

const email = await mailosaur.messages.get(server_Id, { sentTo: user_email, }) expect(email.subject).toEqual(‘Password reset request by [email protected]’) const resetPasswordLink = email.html?.links?.[1].href ?? ” await this.page.goto(resetPasswordLink)

Peerjs how to tell if a connection to a peer has been successfully established

Is there a way with peerjs to tell if a connection has been successfully made when using peer.connect(). Reading the docs the only events emitted for a DataConnection are data, open, close and error. And open is only emitted when you actually send a message using conn.send().

I am trying to create a peer to peer file transfer by sending chunks of data. My current flow is to first connect to the user and save that connection for future use. Then I would like to send them a message that a transfer has been initialized so they can either accept or deny the transfer.

My big problem that I am having is if the user is not currently online there is just a generic error saying cannot connect to user {userid}. There is no success emitted when a connection has been established. So if I were to write a function to connect to a peer then there is really now way of knowing if the connection is successful only if it was unsuccessful. So something like so:

async function connect(to) {
  return new Promise((resolve, reject) => {
    const conn = peer.connect(to)

    // This doesn't exist
    conn.on('success', () => {
      connections.set(to, conn)
      resolve(conn)
    })

    // This does exist
    conn.on('error', (err) => reject(err))
  })
}

Then if I can store the connection I can just grab the connection and send with it.

function send(to, data){
  const conn = connections.get(to)
  if(!conn) throw new Error('No connection available')

  conn.send(data)
}

So currently I have resorted to using the listAllPeers() function to get a list of connected peers. Then running that in a setInterval until the peer has been found. This seems like a bit more work than needs to be done and also requires and extra call to the peer server for no reason other than to check if a peer is available before connecting which seems stupid.

So is there a good way to tell if a connection has been established or am I stuck with my current solution?

Switching tab in Selenium causes page to reload

I’m handling multiple tabs with SeleniumJS. Firstly, it switches to the second tab to handle automation on that, but switching back to the first tab causes the first tab to reload.

My current code of handling it is the standard:

if (handles && handles.length >= 2) {
      try {
        await driver.switchTo().window(handles[0]);

        console.log("Switched back to the first tab");
      } catch (error) {
        console.error("Error switching back to the first tab:", error);
      }
}

I have also tried making it pressing the bind Ctrl+Tab but that still reloaded the page.

Any help is appreciated!

React Developer [closed]

I am react developer but unable to get work via fiverr and upwork Made gigs ,sent proposals,I am react developer but unable to get work via fiverr and upwork Made gigs ,sent proposals,I am react developer but unable to get work via fiverr and upwork Made gigs ,sent proposals,I am react developer but unable to get work via fiverr and upwork Made gigs ,sent proposals.

Why does this div ball not move according to the angle calculated as an offset?

I’m new to front-end learning, and I’m making a simple game to practice what I’ve learned: controlling a tank and firing cannons.
You can use the left and right keys to rotate the tank. At this time, press the up and down keys, and the tank will change its position based on the offset calculated from the current rotation angle. It will no longer just go straight up and down (or straight left and right).
I want it to be able to fire artillery shells: generate a div at the front end of the gun barrel, and then calculate the motion offset based on the angle of the tank’s rotation to move the position of the artillery shell.
But it failed. I found that when the angle was 0-5, the running trajectory of the div did not change, but when the angle of the tank was 6, its launch destination changed a lot. It was like the hands of the clock were stuck. It was motionless in one place, and then suddenly someone moved it with their hands.
My English is not good, I’m not sure if you can understand my question. Any help is appreciated.

HTML:

<!DOCTYPE html>
<html>
<head>
  <title>TankGame</title>
  <style>
    .player-tank, .enemy-tank {
      width: 70px;
      height: 50px;
      position: absolute;
    }
    .tank-body {
      width: 50px;
      height: 50px;
      background-color: green;
      border-radius: 50%;
      position: relative;
      transform-origin: center center;
    }
    .tank-turret {
      width: 6px;
      height: 40px;
      background-color: #696969;
      position: absolute;
      top: -30px;
      left: 22px;
      /* transform-origin: center center; */
    }
    .tank-tread {
      width: 10px;
      height: 50px;
      background-color: black;
      position: absolute;
      bottom: 0;
    }
    #left-tread {
      left: -10px;
    }
    #right-tread {
      right: -10px;
    }

    .hiddenBullet{
      visibility: hidden;
      width: 6px;
      height: 6px;
      background-color: blue;
      position: absolute;
      top: -30px;
      left: 22px;
      /* transform-origin: center center; */
    }
  </style>
</head>
<body>
  <script src="js/tank.js"></script>
  <script src="js/playerTank.js"></script>
  <script src="js/enemyTank.js"></script>
  <script>
    const playerTank = new PlayerTank();
    document.addEventListener('keydown', function(event) {
      switch (event.key) {
        case 'ArrowUp':
        playerTank.move('up');
          break;
        case 'ArrowDown':
        playerTank.move('down');
          break;
        case 'ArrowLeft':
        playerTank.rotateTurret(-1);
          break;
        case 'ArrowRight':
        playerTank.rotateTurret(1);
          break;
        case ' ':
          playerTank.shoot();
          break;
      }
    });
  </script>
</body>
</html>

tank.js:

class Tank {
    constructor(isPlayerTank) {
        //Create Tank Div
        this.element = document.createElement('div');
        this.element.className = isPlayerTank ? 'player-tank' : 'enemy-tank';
        document.body.appendChild(this.element);
        //Tank body
        this.bodyElement = document.createElement('div');
        this.bodyElement.className = 'tank-body';
        this.element.appendChild(this.bodyElement);
        //turret
        this.turretElement = document.createElement('div');
        this.turretElement.className = 'tank-turret';
        this.bodyElement.appendChild(this.turretElement);
        //Tread
        this.leftTreadElement = document.createElement('div');
        this.leftTreadElement.className = 'tank-tread';
        this.leftTreadElement.id = 'left-tread';
        this.bodyElement.appendChild(this.leftTreadElement);

        this.rightTreadElement = document.createElement('div');
        this.rightTreadElement.className = 'tank-tread';
        this.rightTreadElement.id = 'right-tread';
        this.bodyElement.appendChild(this.rightTreadElement);
        //Set an element positioned relative to the car body at the muzzle to facilitate subsequent setting of the initial position of the shell.
        this.hiddenBulletElement = document.createElement('div');
        this.hiddenBulletElement.className = 'hiddenBullet';
        this.bodyElement.appendChild(this.hiddenBulletElement);

        //Initialization orientation
        this.currentRotation = isPlayerTank ? 0 : 180;
        this.element.style.transform = 'rotate(' + this.currentRotation + 'deg)';
        this.step = 10;
        this.bullets = [];
        this.maxBullets = 1;

        this.element.style.left = (window.innerWidth / 2 - 25) + 'px'; 
        this.element.style.top = isPlayerTank ? (window.innerHeight - 80) + 'px' : '0px'; 

        //The generated tank object is stored in a static array to facilitate subsequent traversal.
        Tank.tanks.push(this);
    }

    static tanks = [];

    move(direction){
        console.log('move');
        const angleInRadians = this.currentRotation * Math.PI / 180;
        let deltaX = 0;
        let deltaY = 0;

        switch (direction) {
            case 'up':
                deltaX += Math.sin(angleInRadians) * this.step;
                deltaY -= Math.cos(angleInRadians) * this.step;
                break;
            case 'down':
                deltaX -= Math.sin(angleInRadians) * this.step;
                deltaY += Math.cos(angleInRadians) * this.step;
                break;
        }
        this.element.style.left = (this.element.offsetLeft + deltaX) + 'px';
        this.element.style.top = (this.element.offsetTop + deltaY) + 'px';
    }

    rotateTurret(angle) {
        this.currentRotation = (angle + this.currentRotation) % 360;
        this.element.style.transform = 'rotate(' + this.currentRotation + 'deg)';
        console.log(this.currentRotation);
    }

    shoot() {
        const bullet = document.createElement('div');
        bullet.className = 'bullet';
        bullet.style.width = '6px'; 
        bullet.style.height = '6px'; 
        bullet.style.backgroundColor = 'red';
        bullet.style.position = 'absolute';
        bullet.style.borderRadius = '50%';

        const turretRect = this.hiddenBulletElement.getBoundingClientRect();
        bullet.style.left = turretRect.left + 'px';
        bullet.style.top = turretRect.top + 'px';

        const angleInRadians = this.currentRotation * Math.PI / 180;
        const bulletSpeed = 5;
        bullet.speedX = Math.sin(angleInRadians) * bulletSpeed;
        bullet.speedY = -Math.cos(angleInRadians) * bulletSpeed; 

        bullet.shooterType = this.isPlayerTank ? 'player' : 'enemy';
        bullet.shooter = this;

        document.body.appendChild(bullet);
        this.bullets.push(bullet);

        this.moveBullet(bullet);
    }

    moveBullet(bullet) {
        if (!bullet) return;
        const move = () => {
            bullet.style.left = (bullet.offsetLeft + bullet.speedX) + 'px';
            bullet.style.top = (bullet.offsetTop + bullet.speedY) + 'px';

            //Check whether the shell is out of bounds
            if (bullet.offsetTop > -10 && bullet.offsetTop < window.innerHeight && bullet.offsetLeft > -10 && bullet.offsetLeft < window.innerWidth) {
                requestAnimationFrame(move);
            } else {
                // remove bullet
                bullet.remove();
                this.bullets.splice(this.bullets.indexOf(bullet), 1);
            }
            this.checkCollisions(bullet);
        };
        requestAnimationFrame(move);
    }

    //
    checkCollisions(bullet){
        for(let tank of Tank.tanks){
            if(tank !== bullet.shooter){
                const tankRect = tank.bodyElement.getBoundingClientRect(); 
                const bulletRect = bullet.getBoundingClientRect();

                const dx = (bulletRect.left + bulletRect.right) / 2 - (tankRect.left + tankRect.right) /2;
                const dy = (bulletRect.top + bulletRect.bottom) / 2 - (tankRect.top + tankRect.bottom) /2;
                const distance = Math.sqrt(dx*dx + dy*dy);

                const collisionDistance = (bulletRect.width + tankRect.width) / 2;

                if(distance < collisionDistance){
                    console.log('hit');
                    bullet.remove();
                    this.bullets.splice(this.bullets.indexOf(bullet), 1);
                }
            }
        }
    }
}

PlayerTank and EnemyTank inherit the Tank class, and only pass true and false in the constructor to add tank type information to the tank instance. There are no methods provided by the Tank class that are added/modified.

why ES6 import does not work in plain js files

I have a problem with importing into plain JavaScript files from libs
for example,currently i am trying to learn Redux and i found that i should learn redux toolkit. but when i am trying to import configureStore it shows me an error
importing code:

import { configureStore } from "@reduxjs/toolkit";

error output:

Uncaught TypeError: Failed to resolve module specifier "@reduxjs/toolkit". Relative references must start with either "/", "./", or "../".

this error occured to me first time when i tried to learn “Chart.js” but couldn’t find a solution for it. that’s why i decided to ask you, hoping to find the answer or the final solution to this problem.

…………………………………….

I’m try to build a discord quiz bot, but I’m facing issue with awaitMessages

Here , I am using a JSON to fetch questions, if the question expects a user to type the answer it’s options array will be of size 0.
It’s only the if(question.options.length === 0) block giving issue.

const { SlashCommandBuilder, ActionRowBuilder, ButtonStyle} = require('discord.js');
const { promisify } = require('util');
const readFileAsync = promisify(require('fs').readFile);
const { ButtonBuilder } = require('discord.js');

async function getQuestion() {
    const fileContent = await readFileAsync("questions.json", 'utf8');
    const questions = JSON.parse(fileContent);
    return questions;
}

function getPoints(difficulty) {
    switch (difficulty) {
        case 'easy':
            return 10;
        case 'medium':
            return 20;
        case 'hard':
            return 30;
        default:
            return 0;
    }
}

module.exports = {
    data: new SlashCommandBuilder()
        .setName('quiz')
        .setDescription('Starts the quiz!')
        .addStringOption(option =>
            option.setName('input')
              .setDescription('Enter some text.')
              .setRequired(true)
          ),
    async execute(interaction) {
        try {
            await interaction.reply('Let the quiz begin!');
            let totalPoints = 0;

            const questions = await getQuestion();
            for (let i = 0; i < questions.length; i++) {
                const question = questions[i];
                //the below if is for questions where user need to type answer
                if(question.options.length === 0){
                    const response = await interaction.followUp({content : question.question});
                    
                    const filter = (response) => {
                        return response.user.id === interaction.user.id;
                    };
                
                    try {
                        const answerCollector = await response.awaitMessageComponent({
                            filter,
                            max: 1,
                            time: 10 * 1000, // Allow 30 seconds for the user to respond
                            errors: ['time'],
                        });
                
                        const userAnswer = answerCollector.first().content;
                        const correctAnswer = question.answer;
                
                        if (userAnswer.toLowerCase() === correctAnswer.toLowerCase()) {
                            const points = getPoints(question.difficulty);
                            await interaction.followUp(`Correct! You earned ${points} points.`);
                            totalPoints += points;
                        } else {
                            await interaction.followUp(`Wrong answer! The correct answer is "${correctAnswer}".`);
                        }
                    } catch (error) {
                        console.error(error);
                        await interaction.followUp({
                            content: 'Answer not received within 30 seconds, cancelling.',
                        });
                    }
                    
                }else{
                    const optionsRow = new ActionRowBuilder();
                    for (let j = 0; j < question.options.length; j++) {
                        const button = new ButtonBuilder()
                            .setCustomId(`option_${j}`)
                            .setLabel(question.options[j])
                            .setStyle(ButtonStyle.Primary);
                        optionsRow.addComponents(button);
                    }
                    const response = await interaction.followUp({ content: question.question, components: [optionsRow] });
                    const collectorFilter = i => {
                        return i.user.id === interaction.user.id;
                    };
    
                    try {
                        const confirmation = await response.awaitMessageComponent({ filter: collectorFilter, time: 10_000 });
                        const selectedOption = parseInt(confirmation.customId.split('_')[1], 10);
                        const correctOption = question.answer;
                        confirmation.update({})
                        if (selectedOption === correctOption) {
                            const points = getPoints(question.difficulty);
                            await interaction.followUp(`Correct! You earned ${points} points.`);
                            totalPoints += points
                        } else {
                            await interaction.followUp(`Wrong answer!, The correct answer is option:${correctOption+1}`);
                            // break;
                        }
                    } catch (e) {
                        console.log(e);
                        await interaction.followUp({ content: 'Answer not received within 10secs, cancelling', components: [] });
                    }         
                }
                    
            }
            await interaction.followUp(`Quiz completed! You earned ${totalPoints} points.`);

        } catch (error) {
            console.log(error);
        }
    },
};

It displays the question, but the user answer is not captured. It moves to the catch block everytime, without even executing the filter function.

Create a JS Date object when local time is given as argument

I need to create a JS Date object when the date and time is given in local timezone. i.e. if the time in India Standard Time (GMT+05:30) is 2024-Feb-04 00:00:00, the time in GMT is 2024-Feb-03 18:30:00. Then the date should created as 2023-02-23T18:30:00.000Z.

Consider a local date as 30th October 1999. If the local time zone is India Standard Time, the offset is GMT+0600. For a latest date i.e. 30th October 2023, the offset for the time zone is GMT+0530.

I Found that there are several DST Changes in this time zone.

My previous approach for create the JS Date object was:

const timezone = '+05:30';

toDate(year, month, date): Date {
    return new Date(
      `${year}-${month.toString().padStart(2, "0")}-${date
        .toString()
        .padStart(2, "0")}T00:00:00${timezone}`
    );
}

As there are several DTS changes in this time zone, it is not practical to change the function to consider the date and select the timezone.

I cannot use any library like moment.

How can I create the JS Date Object?

how to get unique key from firebase?

So I am working on a website of restaurant using firebase.
The structure is like this
food
dessert
item1
item2
item3

i want the data to be aaded with same key continuation . This way
food
dessert
item1
item2
item3
item4
item5

and so on….

let nextKey = 1;

        // Retrieve data once to find the next available key
        get(ref(dessertsRef)).then((snapshot) => {
          const keys = Object.keys(snapshot.val() || {});
          const maxKey = keys.reduce(
            (max, key) => Math.max(max, parseInt(key.replace("item", ""))),
            0
          );
          nextKey = maxKey + 1;

          // Add dessert data to Firebase with the next available key
          set(ref(dessertsRef, `item${nextKey}`), {
            name: name,
            description: description,
            price: price,
            type: type,
            imageUrl: imageUrl,
          });

Tried this

MongooseError: Model.findOne() no longer accepts a callback at Function in 2024

my codes here


const express = require("express");
const app = express();
const mongoose = require("mongoose");
 const UserModel = require("./models/Users");

const cors = require("cors");

app.use(express.json());
app.use(cors());

mongoose.connect(
    "mongodb+srv://user123:<password>@cluster0.16wokcq.mongodb.net/merntutorial?retryWrites=true&w=majority"
);

app.get("/getUsers", (req, res) => {
   UserModel.find({}, (err, result) => {
    if (err) {
      res.json(err);
    } else {
      res.json(result);
    }
  });
});


app.listen(3001, () => {
  console.log("SERVER RUNS PERFECTLY!");
});

I’m a beginner guy about mern stack project, I know it’s common error about mongoose but I search so many solutions but I these didn’t work for me: (