2fa totp code does not working in nodejs even though its good

when i enabled 2fa and added the secret to google authenticator on my phone i try to login, but i keep getting an error message that says invalid 2fa code. how can i fix it? the code is indeed ok…

this is my code:

const express = require("express");
const session = require("express-session");
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const speakeasy = require("speakeasy");
const flash = require("express-flash");
const app = express();
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const authenticator = require("otplib");
// Use sessions to track login status
app.use(
  session({
    secret: "your-secret-key",
    resave: false,
    saveUninitialized: false,
  })
);

// Initialize Passport and session
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(bodyParser.urlencoded({ extended: true }));

mongoose
  .connect("mongodb://localhost:27017/2fa", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log("MongoDB connected successfully");
  })
  .catch((err) => {
    console.error("MongoDB connection error:", err);
  });

// Create a User model/schema
const User = mongoose.model("User", {
  username: String,
  password: String,
  secret: String,
  is2FAEnabled: Boolean,
  token: String,
});

// Passport local strategy for authentication
passport.use(
  new LocalStrategy(async function (username, password, done) {
    try {
      const user = await User.findOne({
        username: username,
        password: password,
      }).exec();

      if (!user) {
        return done(null, false, { message: "Incorrect username or password" });
      }

      return done(null, user);
    } catch (err) {
      return done(err);
    }
  })
);

// Serialize user for session
passport.serializeUser(function (user, done) {
  done(null, user.id);
});

// Deserialize user from session
passport.deserializeUser(async function (id, done) {
  try {
    const user = await User.findById(id).exec();
    done(null, user);
  } catch (err) {
    done(err);
  }
});

// Middleware to check if user is authenticated
function isAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.redirect("/login");
}

// Routes

// Dashboard route
app.get("/dashboard", isAuthenticated, async (req, res) => {
  try {
    const user = await User.findById(req.user.id);

    if (user && user.is2FAEnabled) {
      return res.redirect("/verify-2fa"); // Redirect to verify-2fa if 2FA is enabled
    } else {
      return res.send("Dashboard Page"); // Render dashboard if 2FA is not enabled
    }
  } catch (error) {
    console.log(error);
    res.redirect("/"); // Fallback redirect to home in case of an error
  }
});

app.get("/", (req, res) => {
  res.send("Home Page");
});

// Login route
app.post(
  "/login",
  passport.authenticate("local", {
    successRedirect: "/dashboard", // Redirect to dashboard by default
    failureRedirect: "/login",
    failureFlash: true,
  })
);

// Logout route
app.get("/logout", (req, res) => {
  req.logout(function (err) {
    if (err) {
      // Handle error, if any
      return res.status(500).send("Internal Server Error");
    }
    // Redirect to the home page or any other page after successful logout
    res.redirect("/");
  });
});

// Enable 2FA for a user user1 secret = MZFXORCDNZKFOL23INLTSSBQMEVHG6BQ / HBLVIKDLN4SEE6TSKJSWWY3SGVKDO3DX
app.get("/enable-2fa", isAuthenticated, async (req, res) => {
  try {
    const secret = speakeasy.generateSecret({ length: 20 });
    // Use findOneAndUpdate to update the user in the database
    await User.findOneAndUpdate(
      { _id: req.user.id },
      { secret: secret.base32, is2FAEnabled: true }
    ).exec();
    res.send(`2FA Enabled. Save this secret: ${secret.base32}`);
  } catch (error) {
    console.error(error);
    res.status(500).send("Internal Server Error");
  }
});

// Authenticate using 2FA
app.post(
  "/login-2fa",
  passport.authenticate("local", {
    successRedirect: "/verify-2fa",
    failureRedirect: "/login",
    failureFlash: true,
  })
);

// Verify 2FA page
app.get("/verify-2fa", isAuthenticated, (req, res) => {
  res.send(`
      <html>
        <head>
          <title>Verify 2FA</title>
        </head>
        <body>
          <h2>Verify 2FA Page</h2>
          <form method="post" action="/verify-2fa">
            <label for="totp">Enter TOTP Code:</label>
            <input type="text" id="totp" name="totp" required>
            <button type="submit">Verify</button>
          </form>
        </body>
      </html>
    `);
});

// Verify 2FA code
app.post("/verify-2fa", isAuthenticated, async (req, res) => {
  try {
    const user = await User.findById(req.user.id);
    const isValid = speakeasy.totp.verify({
      secret: user.secret,
      encoding: "base32",
      token: req.body.totp,
    });
    //console.log("User ID:", req.user.id);
    //console.log("User Secret:", user.secret);
    //console.log("is2FAEnabled:", user.is2FAEnabled);
    //console.log("Received TOTP:", req.body.totp);
    if (isValid) {
      res.redirect("/dashboard");
    } else if (!isValid) {
      res.send("Invalid 2FA code. Try again.");
    } else {
      res.send("some error my nigga");
    }
  } catch (error) {
    console.error(error);
    res.status(500).send("Internal Server Error");
  }
});

// Login page
app.get("/login", (req, res) => {
  res.send(`
      <html>
        <head>
          <title>Login</title>
        </head>
        <body>
          <h2>Login Page</h2>
          <form method="post" action="/login">
            <label for="username">Username:</label>
            <input type="text" id="username" name="username" required>
            <br>
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" required>
            <br>
            <button type="submit">Login</button>
          </form>
        </body>
      </html>
    `);
});

app.get("/register", (req, res) => {
  res.send(`
      <html>
        <head>
          <title>Register</title>
        </head>
        <body>
          <h2>Registration Page</h2>
          <form method="post" action="/register">
            <label for="username">Username:</label>
            <input type="text" id="username" name="username" required>
            <br>
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" required>
            <br>
            <button type="submit">Register</button>
          </form>
        </body>
      </html>
    `);
});

app.post("/register", (req, res) => {
  const { username, password } = req.body;

  // Check if the username already exists
  User.findOne({ username: username })
    .exec()
    .then((existingUser) => {
      if (existingUser) {
        return res.send(
          "Username already exists. Please choose a different one."
        );
      }

      // Create a new user and save to the database
      const newUser = new User({
        username: username,
        password: password,
        secret: speakeasy.generateSecret({ length: 20 }).base32,
        is2FAEnabled: false,
      });

      return newUser.save();
    })
    .then(() => {
      res.send("Registration successful. You can now log in.");
    })
    .catch((err) => {
      console.error(err);
      res.status(500).send("Internal Server Error");
    });
});

// Start server
const PORT = 80;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

without 2fa enabled a user can login and logout without any problem. but for some reason i keep getting the “invalid 2fa code” error message… what to do?

How to merge two images in javascript? [closed]

I’m making a drag and drop game using images in JavaScript where If I drag the image 1 to image 2, image 2 shrinks or expands in size, and image 1 just disappears. Or is it possible to merge the two images? Or is there another method? I already did the drag and drop on the images but I’m stuck in the merging part.

Firebase web modular API – initializeApp()

I am switching over to the JavaScript web modular API from JavaScript namespaced (compat).
My code is a Firebase Function with a http trigger running on GCP, so the code ‘lives’ in the GCP infra. My thought is that, because of this, I do not need to specify a bunch of data to initialise the App and Database, which would be the case if my code ran on ReactJS, or any other front end framework.

In my old code I simply initialised the app in a file called firebase-db that was included wherever needed. This also gave me a handle to the database. The database handle is no longer needed with the modular API.

// This is the old namespaced code
const admin = require("firebase-admin");

const app = admin.initializeApp();
const database = admin.database(app);
module.exports = database;

In my new code I do not have this file and I am simply using the below code in my files.

const { ref, getDatabase, get } = require("firebase/database");
...

However, this does not work.
I get an error that clearly states that the ‘App’ need to be initialised.

FirebaseError: Firebase: No Firebase App ‘[DEFAULT]’ has been created – call initializeApp() first (app/no-app)

My new firebase-db file looks like this; but it does not work:

// This is the new modular code
const { initializeApp } = require("firebase-admin");
const { getDatabase } = require("firebase/database");

const app = initializeApp(); //<-- This line generates an error!
const database = getDatabase(app);

module.exports = database;

The call initializeApp(); generates error:

TypeError: Cannot read property ‘INTERNAL’ of undefined

I have tied to look into the documentation, but cannot find any good examples on how to initialise the App so that I can get the Dabase handle using getDatabase().

https://firebase.google.com/docs/database/admin/retrieve-data#node.js_19
https://firebase.google.com/docs/database/web/read-and-write#web-modular-api_5
https://firebase.google.com/docs/reference/js/database.md#equalto_51c2c8b

Any help much appreciated! /K

Why is javascript array does not work properly? Is it javascript bug? [closed]

If I call foo function below with n = 3, I got return value: [4, 4, 4] instead of [4, 2, 0]. Both line 2 or line 3 will give same result.

function foo (n) {
  // const result = new Array(n).fill(0)
  const result = Array.from({length: n}, () => 0)
  for (let i = 0; i < n; i++) {
    result[i] = 2 * (n - 1)
  }
  return result
}

Is this javascript bug? Or shortcoming?
How do I make an array as I want it to normally behave?

Returning default data not updated data [duplicate]

I am trying to iterate over an array of objects which I then need to process another array of items that I need to query the database for and process the data to push into an array while updating a value in the array.

The below code does what I want in the sense of the order, the lookups, data processing etc however it does not allow me to return the updated seriesData to the API endpoint caller.

// Setup process
let seriesData = [];
const seriesDataTemplate = {
    x: "",
    y: 0,
    goals: [
        {
            name: "",
            value: 0,
                strokeHeight: 5,
            strokeColor: "#775DD0",
        }
    ]
};

// Some code not included that populates seriesData with seriesDataTemplate as the base for the object with x, y, goals.name and goals.value updated

// Area with the problem
itemIds.forEach(async itemId => {
    subArr.forEach(async sI => {
        const category = sI.category.toUpperCase().replace(/ /g, "_");
        const t = await getT(sI, category);
        sI.t = t;
        const total = t.reduce((acc, ta) => {
            return acc + ta.amount;
        }, 0);
        await updateSeriesData(sI, total);
    });
});

// Supporter function
async function updateSeriesData(sI, total) {
    let foundIndex = seriesData.findIndex(obj => obj.x === sI.category);
    seriesData[foundIndex].y = total;
}

This all runs inside an express.js route that is async and right after the end of this code I return seriesData to the user which only contains the template code

Adding 2 JSONs together with some manipulation in JavaScript

I’m trying to add/combine 2 JSONs together without losing any duplicate information, simply adding the one to the other with inserting title for each JSON before adding them together. I’ve seen lot of ways of doing it none worked for my JSONs below, tried the concat method and spread operator and they didn’t work.

const json1 = [{"title": "1"}, {"title": "2"}]
const json2 = [{"title": "2"}, {"title": "3"}]

Expected result:

const combined = {"json1":[{"title": "1"}, {"title": "2"}], "json2":[{"title": "2"}, {"title": "3"}]}

In laravel update image file without using controller

i am having a problem with my code.
i have a canvas image and i want insert markers with text and picture for “n” element, because i would like the user choose how many point insert in it.
So, for the text I have done, because i sum the previous text with new and use a separator as “$”, the in Model Member i split it and display it for every point.
But, for the file is different because I want to update these in folder path(/public/images), but doens’t work. Below, some parts about my code:

var loadFile = function(event) {
  var reader = new FileReader();
    reader.onload = function(){
  var output = document.getElementById('output');
    output.src = reader.result;
  var file = event.target.files[0]; 
  var url = URL.createObjectURL(file);



 var extension = file.name.split('.').pop();
    filename = Date.now() + '.' + extension;

    var data = new FormData();
data.append( "json", JSON.stringify( file ) );


    fetch("/public/images/",{
    method:"POST",
    headers: {'Content-Type':'application/x-www-form-urlencoded'},
    body:data
  }).then(function(res){ return res.json(); })
.then(function(data){ alert( JSON.stringify( data ) ) })

The result in console is:”POST http://127.0.0.1:8000/public/images/ 404 (Not Found)”
I understood that the move of file is not happens.

for the text:

for (var k = 0; k < Markers.length; k++) {
commentinegative=commentinegative+Markers[k].comment.toString()+'*';

Some ideas? thank you.

React Leaflet map not Re-rendering

I’m encountering an issue with my React application where the Leaflet map component is not re-rendering even though the data it depends on has changed. Here’s the structure of my code:
App.js

 let [ip_address,setIp] = useState();
   let [ipData, setipData] = useState({});
   let [errorMessage, setErrorMessage] = useState('');
   const inputRef = useRef("");
   //Get ip of user;
   const getData = async () => {
    const res = await axios.get("https://api.ipify.org/?format=json");
    console.log(res.data);
    setIp(res.data.ip);
  }
   useEffect(() => {
    getData();
   }, []);

   useEffect(() => {
    if (ip_address){
      logData(ip_address)
      .then(values => {
        if (values.error_msg) {
          setErrorMessage(values.error_msg);
          setipData({});
        } else {
          setErrorMessage("");
          setipData(values || {});
        }
      })
      .catch(error => {
        console.error(error);
        setErrorMessage("An error occurred while fetching data.");
        setipData({});
      });
    }
   }, [ip_address])

 return (
    <div className="App">
      <header className="App-header">
        {/* Header content */}
      </header>
      <Map className="Map" ipData={ipData} errorMessage={errorMessage} />
    </div>
  );
}

Map.js

else  if (!Object.keys(ipData).length) {
        console.log("waiting");
    }
    else{
        const longitude = ipData["lat"]
        const latitude = ipData["lng"];
        const position = [longitude, latitude];
        const customIcon = L.divIcon({
            html:
            `
            <svg xmlns="http://www.w3.org/2000/svg" width="46" height="56" style="background: transparent;">
            <path fill-rule="evenodd" d="M39.263 7.673c8.897 8.812 8.966 23.168.153 32.065l-.153.153L23 56 6.737 39.89C-2.16 31.079-2.23 16.723 6.584 7.826l.153-.152c9.007-8.922 23.52-8.922 32.526 0zM23 14.435c-5.211 0-9.436 4.185-9.436 9.347S17.79 33.128 23 33.128s9.436-4.184 9.436-9.346S28.21 14.435 23 14.435z"/>
        </svg>    
            `,
            iconSize: [10, 16]
        })
        return (
            <MapContainer center={position} zoom={15}>
            <TileLayer
            attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            <Marker position={position} icon={customIcon}></Marker>
            </MapContainer>
        );

I expect the Leaflet map component to re-render whenever there’s a change in the ipData prop passed to it. This includes changes in latitude and longitude coordinates. I chechek and it seems that the icon gets moved to the correct location but the map itself remains static, displaying the old location.

nextjs error handling – getting The above error occurred in the component:

I’m getting a strange error in the next.js – my error bound is giving me an error that the exception is not caught, everything else seems to be working (my error renders and reset works):

login.tsx:

import {tryLogin} from '@/app/lib/auth';

export default async function Page() {
    "use server"

    return (
        <div className="max-w-md mx-auto bg-white rounded-xl shadow-md overflow-hidden md:max-w-2xl">
            <div className="p-8">
                <div className="uppercase tracking-wide text-sm text-indigo-500 font-semibold text-center">Login
                    Required
                </div>
            </div>
            <form action={tryLogin} className="bg-white shadow-md rounded px-8 pt-6 pb-8">
                <div className="mb-4">
                    <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="username">
                        Username
                    </label>
                    <input
                        className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                        id="username" type="text" placeholder="Username"/>
                </div>
                <div className="mb-6">
                    <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="password">
                        Password
                    </label>
                    <input
                        className="shadow appearance-none border border-red-500 rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline"
                        id="password" type="password" placeholder="******************"/>
                </div>
                <div className="flex items-center justify-between">
                    <button
                        className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
                        type="submit">
                        Sign In
                    </button>
                    <a className="inline-block align-baseline font-bold text-sm text-blue-500 hover:text-blue-800"
                       href="#">
                        Forgot Password?
                    </a>
                </div>
            </form>
        </div>

    );
}

error.tsx:

'use client' // Error components must be Client Components

import { useEffect } from 'react'
import { useRouter } from 'next/navigation'

export default function Error({
                                  error,
                                  reset,
                              }: {
    error: Error & { digest?: string }
    reset: () => void
}) {
    useEffect(() => {
        console.log("HERE:::" + error)
    }, [error])

    return (
        <div>
            <h2>Login Failed</h2>

            <button
                className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline mt-1"
                onClick={
                    // Attempt to recover by trying to re-render the segment
                    () => reset()
                }
            >
                Try again
            </button>
        </div>
    )
}

auth.tsx: (yes, it’s throwing an error every time)

import 'server-only'

import { redirect } from 'next/navigation'
export async function tryLogin(username: string, password: string){
    "use server"
    return new Promise<string>(
        (accept, reject) => {
            reject("Login failed")
            // if(new Date().getTime() % 2 === 0){
            //     // redirect("/")
            //     reject('DUMMY_TOKEN')
            // } else {
            //     reject('Login failed')
            // }
        }
    )
}

Browser console:

XHRPOST
http://localhost:3000/login
[HTTP/1.1 500 Internal Server Error 23ms]

Uncaught Error: Error: Login failed 4 react-server-dom-webpack-client.browser.development.js:1792:14
The above error occurred in the <RedirectErrorBoundary> component:

RedirectErrorBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/redirect-boundary.js:73:9
RedirectBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/redirect-boundary.js:81:24
NotFoundBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/not-found-boundary.js:84:62
LoadingBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/layout-router.js:335:76
ErrorBoundaryHandler@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/error-boundary.js:114:9
ErrorBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/error-boundary.js:161:67
InnerScrollAndFocusHandler@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/layout-router.js:152:9
ScrollAndFocusHandler@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/layout-router.js:227:37
RenderFromTemplateContext@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/render-from-template-context.js:16:44
OuterLayoutRouter@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/layout-router.js:354:209
InnerLayoutRouter@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/layout-router.js:243:18
RedirectErrorBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/redirect-boundary.js:73:9
RedirectBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/redirect-boundary.js:81:24
NotFoundErrorBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/not-found-boundary.js:76:9
NotFoundBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/not-found-boundary.js:84:62
LoadingBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/layout-router.js:335:76
ErrorBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/error-boundary.js:161:67
InnerScrollAndFocusHandler@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/layout-router.js:152:9
ScrollAndFocusHandler@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/layout-router.js:227:37
RenderFromTemplateContext@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/render-from-template-context.js:16:44
OuterLayoutRouter@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/layout-router.js:354:209
main
body
html
RedirectErrorBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/redirect-boundary.js:73:9
RedirectBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/redirect-boundary.js:81:24
NotFoundErrorBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/not-found-boundary.js:76:9
NotFoundBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/not-found-boundary.js:84:62
DevRootNotFoundBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/dev-root-not-found-boundary.js:33:24
ReactDevOverlay@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/react-dev-overlay/internal/ReactDevOverlay.js:84:9
HotReload@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/react-dev-overlay/hot-reloader-client.js:307:37
Router@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/app-router.js:181:114
ErrorBoundaryHandler@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/error-boundary.js:114:9
ErrorBoundary@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/error-boundary.js:161:67
AppRouter@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/app-router.js:536:47
ServerRoot@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/app-index.js:129:24
RSCComponent
Root@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/app-index.js:145:24

React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundaryHandler. app-index.js:33:21
HERE:::Error: Error: Login failed

ViewTransitions break inView animation (Motion One)

I’m using ViewTransitions to fade between pages and use motion ones inView animation on headings to fade them in. They only work on the first page load.

This is what i tried:

<script>
      import { animate, inView } from 'motion';

      const doFadeIn = (target: Element) =>
        animate(
          target,
          {
            opacity: [0, 1],
            transform: ['translateX(-10px)', 'translateX(10px)'],
          },
          { duration: 0.5, delay: 0.1 }
        );

      inView('h2', (el) => {
        doFadeIn(el.target);
      });
</script>

and the ViewTransition is from Astro

<html transition:animate="fade">
  <head>
    <title> My Page </title>
    <ViewTransitions />
  </head>
</html>

On The first page load it works as expected but after navigating, the inView doesn’t trigger anymore.

how to know when popup is closed in react leaflet?

how to know when popup is closed in react leaflet, i need to detect when the popup is closed to emit to the server side to stop streaming. so i need to know how when the popup is close. and onclick and on close are not a functions in react leaflet.

  <MapContainer  className ='map-display'center={[31.5, 35]} zoom={8} maxZoom={17} minZoom={7} attributionControl={false} >
    <TileLayer
      url="http://localhost:8000/zzz/clients/mapData/{z}/{x}/{y}.png" // Adjust the URL to match your server endpoint
    />    
     {/* placing zoom on the map and makeing that the map state is saved when clicking on the map container  */}
    <RenderBaseZoom LatLng={latLng( index?index.x?index.x:31.5:31.5,index?index.y?index.y:35:35)} zoom={zoom?zoom:8} setZoom={setZoom} setIndex={setIndex}/>
    
  {positoionList.map((marker, index) => (
      <Marker key={index} position={[marker.x, marker.y]} icon={customIcon} >
        <Popup className="fullscreen-popup" >Camera {index + 1} configuration 
       
          <StreamVideoDiv socket={socket} startEffect={closed} />
          <button className='returnButton' onClick={()=>handleDisconnect()}><FaMapLocationDot /></button>
        </Popup>
      </Marker>
    ))}
    <MapClickHandler />
    
  </MapContainer>

i expect to get a correct function that do something when popup is closed

Loading of Google Maps API in a JavaScript app

I have a web app that uses Google Maps. The app isn’t displaying the Map all the time. And not always in the same place. What is the best practice for loading and unloading the Map on a page?

The initial function makes the first setup, but knowing what to do afterwards is confusing. For instance, if the user clicks something, the Map pops up with maybe 100 markers. Then he closes the Map. Then, he opens the Map again with maybe 100 different markers and some overlays.

Should I run a new init every time the map loads?

If I don’t, I don’t understand how to get access to, for instance, the AdvancedMarkerElement the second time around.

Here is Google’s sample code:

// Initialize and add the Map
let Map;

async function initMap() {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };
  // Request needed libraries.
  //@ts-ignore
  const {Map} = await google.maps.importLibrary("maps");
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

  // The Map, centered at Uluru
  map = new Map(document.getElementById("map"), {
    zoom: 4,
    center: position,
    mapId: "DEMO_MAP_ID",
  });

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerElement({
    map: Map,
    position: position,
    title: "Uluru",
  });
}

initMap();

What I need is a more dynamic way of opening the Map. In this example, markers and everything is decided immediately.

nextTick() return and its use with then

I don’t quite understand what nextTick() is good for (it seem to be related to update of DOM & vDOM), but what interests me is in all that is does it returns a promise ?

in bellow example it is followed by then() which as far as I know should be only used with promises isn’t it ? (i.e promise.then())

    open() {
      this.$nextTick().then(() => {
        this.menu = true;
      });
    },

In ChartJS 3.9.1 is there any solution, to show only gridlines and labels at a specific point?

I’m using ChartJs 3.9.1 to visualize my data. I need to show the day when the atcual value was created, so I chose the solution in which I mark the days with colorcodes in fill bckColor. So far so good.

But i found it still confusing, as the X axis labels doesn’t fit with the color changes. So my question is, is there any way to show the vertical grid lines, and its label only at the point, where the colorcode (the day index of the value) changes?

Thanks for nay help!

Here’s a sample code:

function setCharts() {

    const colorDays = ['#54bebe', '#76c8c8', '#98d1d1', '#badbdb', '#dedad2', '#e4bcad', '#df979e', '#d7658b', '#c80064'];

    let dataRandom = fillRandomValues();

    const tab = document.getElementById('tabCharts');
    tab.innerHTML = '';

    let ctx = document.createElement('canvas');
    ctx.id = 'canvasChart';

    new Chart(ctx, {
        
        type: 'line',
        data: {

            idxDays: dataRandom.listIdxDays,
            labels: dataRandom.listIdxValues,
            datasets: [{
                
                label: `example`,
                fill: true,
                backgroundColor: '#54bebe',
                borderColor: '#54bebe',
                borderWidth : 2,
                pointRadius: 0,
                data: dataRandom.listValues,
                segment: {

                    backgroundColor: (ctx) => (colorDays[ctx.chart.data.idxDays[ctx.p0DataIndex]]),
                }
            }]
        },
        options: {

            responsive: true,
            maintainAspectRatio: false,
            scales: {

                y: {

                    beginAtZero: true          
                }
            } 
        }
    });

    tab.appendChild(ctx);
}

function fillRandomValues() {

    let data = {

        listValues: [], // actual values
        listIdxValues: [],  // idx of the value in the array (1, 2, 3...) for the chart data.labels
        listIdxDays: [], // the idx of the day the value created (0:mon, 1:tue...) for the color coding
        listIsDayChanged: [], // if the day of the values changes (true, false)
    };

    let dayActual = 0;

    for (let d = 0; d < 100; d++) { // 100 random value

        let rand = 50 + (Math.floor(Math.random() * 10));

        if (rand < 55) {

            dayActual == 6 ? dayActual = 0 : dayActual++;
            data.listIsDayChanged[d] = true;
        } else {

            data.listIsDayChanged[d] = false;
        }

        data.listValues[d] = rand;
        data.listIdxDays[d] = dayActual;
        data.listIdxValues[d] = d;
    }

    return data;
}

and the HTML:

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

<div id="tabCharts" class="tabContent" style="display: none; width: 1000px; height: 500px;"></div>