Vue3 setup variable not declared when accessing in template

In my vue file, my template has a div which uses v-for on an “items” array to load each element of the array visually. I have the “items” array defined in setup() using the composition API, and I return “items” in setup. Even with all this, when I try to render or load the page, it errors stating “main.js:30 ReferenceError: items is not defined”

In my template

<div v-for="product in items" :key="product.id" class="group relative">

In my <script>

export default {
      setup() {
        let items = ref([]);

        onMounted(()=> {
        //here i retrieved data from firebase and pushed to items
        });

        return { items };

      }
    }

My error in dev tools is “main.js:30 ReferenceError: items is not defined”

(edited to include minimal reproducible example below)

<template>
  <div v-for="product in items" :key="product.id" class="group relative" >{{product.id}}</div>
</template>

<script >
import { ref,onMounted } from 'vue'
export default {
      setup() {
        let items = ref([]);
        onMounted(()=> {
        items.value = [{id:'a'}]
        });
        return { items };
      }
    }
</script>

Stringify BigInt as a number instead of string

Since JSON.stringify does not support BigInts, a common suggestion is to patch toJSON into its prototype or use a replacer function to the likes of (k, v) => typeof v === 'bigint' ? v.toString() : v. The problem is, this stringifies BigInts as strings and not numbers { foo: 123n } becomes { "foo": "123" } instead of { "foo": 123 }.

I have a requirement to produce a payload for an API that expects a number, and that number can exceed the largest safe integer possible in JS. Is there any way to do that, besides building the string myself (or stripping out the quotes afterwards)?

Why can’t I change one array without it changing the other? [USING .PUSH; NOT TRYING TO ASSIGN THE VALUE OF ONE ARRAY TO ANOTHER]

let nameList = document.getElementById("name-list").childNodes;
  nameList.forEach((x) => {
    if (x.className === "name-container") {
      x.childNodes.forEach((y) => {
        if (y.tagName === "DIV") {
          houses.push([y.id.slice(8)]);
          availRecipients.push([y.id.slice(8)]);
        }
      });
    }
  });

In my code, I’m grabbing information from the DOM and putting it in an array. I wanted to create two arrays with the same data so I could delete items from one array and still have the original array intact to reference against. So I have ‘houses’ and ‘availRecipients’. I ran into a problem where if I spliced data out of ‘availRecipients’ it also mutated the ‘houses’ array. To solve the problem, I created a separate function to deep copy the ‘houses’ array in order to create the ‘availRecipients’ array, and everything works as intended now. But I’d like to understand better. Can someone please explain to me why populate the two arrays with data at the same time in the same function makes them references to each other and not separate arrays? Both the original function and the deep copy function are using ‘.push’, so I really don’t get what’s happening here. I’m not creating the ‘availRecipients’ array by simply ‘availRecipients=houses’; I understand why that doesn’t work.

Angular 17 and AngularFire 17 Error when trying to use service

I have been stuck with this issue for a while now as I’m not familiar with Angular 17 new standalone default without app.module.ts

This is my app.config.ts

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes), 
    provideAnimations(), 
   importProvidersFrom(provideFirebaseApp(() => initializeApp(environment.firebase))),  
   importProvidersFrom(provideAuth(() => getAuth())), 
   importProvidersFrom(provideAnalytics(() => getAnalytics())), 
   ScreenTrackingService, UserTrackingService, 
   importProvidersFrom(provideFirestore(() => getFirestore())), 
   importProvidersFrom(provideStorage(() => getStorage())),
   importProvidersFrom(AngularFireModule),
   importProvidersFrom(AngularFireAuthModule),
   importProvidersFrom(AngularFirestoreModule),
   importProvidersFrom(AngularFireStorageModule),
   importProvidersFrom(AngularFireDatabaseModule),
  ]
};

This is my auth.service.ts

import { Injectable, NgZone, isDevMode } from '@angular/core';
import { User } from '../services/user';
import * as auth from 'firebase/auth';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import {
  AngularFirestore,
  AngularFirestoreDocument,
} from '@angular/fire/compat/firestore';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})

export class AuthService {
  userData: any; 
  constructor(
    public afs: AngularFirestore, 
    public afAuth: AngularFireAuth,
    public router: Router,
    public ngZone: NgZone, 
    public db: AngularFirestore

  ) {
...
}

When I try to use this service in the component. It thrown this error.

export class SignupComponent {
  
  constructor(
    public authService: AuthService
  ) { }



[Error] ERROR – NullInjectorError: R3InjectorError(Standalone[_AppComponent])[_AuthService -> _AuthService -> _AngularFirestore -> InjectionToken angularfire2.app.options -> InjectionToken angularfire2.app.options]: 
  NullInjectorError: No provider for InjectionToken angularfire2.app.options!
NullInjectorError: R3InjectorError(Standalone[_AppComponent])[_AuthService -> _AuthService -> _AngularFirestore -> InjectionToken angularfire2.app.options -> InjectionToken angularfire2.app.options]: 

My package.json

  "dependencies": {
    "@angular/animations": "^17.0.0",
    "@angular/common": "^17.0.0",
    "@angular/compiler": "^17.0.0",
    "@angular/core": "^17.0.0",
    "@angular/fire": "^17.0.1",
    "@angular/forms": "^17.0.0",
    "@angular/platform-browser": "^17.0.0",
    "@angular/platform-browser-dynamic": "^17.0.0",
    "@angular/platform-server": "^17.0.0",
    "@angular/router": "^17.0.0",
    "@angular/ssr": "^17.0.9",
    "express": "^4.18.2",
    "firebase": "^10.7.1",
    "rxjs": "~7.8.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.14.2"
  },

From what I understood, the problem is it cannot find the module. But I did put it in the providers in the app config. Isn’t this the way it supposed to be? Or should I add it to the itself services? if so, How should I do it?

Thank you so much in advance!

How do I make a button in visual studio code connect with the bluetooth module component?

Currently, I am having a hard time trying to figure out how I can get the Bluetooth module, which is a Bluetooth component connect to the Arduino to collect data when I click on a button, I programmed in a website in Visual Studio Code.

I tried a different approach to this problem using a website called MIT App Inventor to develop a basic mobile app with a button that would send data to the BT module. Unfortunately, the android device I’m using wouldn’t respond due to an error. At the same time, I was expecting the piezo buzzer to generate beeping sound effects once I clicked the button in the software.

Handling 404 errors with TDD, JEST, SQL

I am working with endpoints using express servers and queries with SQL while testing with JEST.
One of my tests should check that in case the user access a path that leads to something non-existent in the database should return a 404 error together with a ‘Not found’ message. Test is as follows:

test.only("400- Responds with a 'Not found' message", () => {
    return request(app)
      .get("/api/aerticless") //<< should be /api/articles
      .expect(404)
      .then(({ body }) => {
        expect(body.msg).toBe("Not found");
      });

This test is is verifying that the following model sends the appropriate data to the controller to deal with the response, the rows from the queried table.

function getArticles() {
return db
.query(
  `SELECT 
  articles.article_id,
  articles.title, 
  articles.topic,
  articles.author,
  articles.created_at, 
  articles.votes,
  articles.article_img_url, 
  COUNT(comments.comment_id) AS comment_count
  FROM articles 
  JOIN comments ON 
  articles.article_id = comments.article_id 
  GROUP BY articles.article_id`
)
.then(({ rows }) => {
  if (rows.length === 0) {
    return Promise.reject({ status: 404, msg: "Not found" });
  }
  return rows;
});
}

In case there is an error, the if statement will reject the promise sending the error to be dealt with. which is going to trigger the next function within the catch block in the controller:

function fetchArticles(req, res, next) {
 getArticles()
.then((data) => {
  res.status(200).send({ articles: data });
})
.catch((err) => {
  next(err);
});
}

The followings are the error handing function invoked in app.use() in the app.js file:

exports.handle400s = (err, req, res, next) => {
 if (err.status === 404) {
 res.status(404).send({ msg: "Not found" });
 } else if (err.status === 400) {
res.status(400).send({ msg: "Bad request" });
 }
};

The problem: This is precisely a similar test I did before for a different endpoint, only that this time and even though it is actually expecting a 404, it is failing with the following message
enter image description here

From within the test, I console.log(body) and it throws an empty object when I am actually expecting an empty array. I am not entirely sure why this is happening, wondering if someone could point out where I am making mistakes in my code.

For loop using ejs in express node js app not outputting data but not showing any errors

I have for loop in javascript which im using to output all the users of the database using ejs. The code is shown below. This is in a express/node js app and am using sql to store data

                <div class = "Contacts">
                    <% for(let person in persons) { %>
                        <h2><%= persons[person]['fname'] %></h2>
                    <% } %>
                </div>

The data is in json and looks like this
enter image description here
The for loops is not printing anything but im also not being told any error in the command prompt

I expected the names to be printed out but they are not. Can anyone see my problem?

Add captions over the thumbnails in fancybox 3

I’m using the following code to create a number of different fancybox galleries. I am using Fancybox V3. I want the captions of the videos to also show up on the thumbnails at the bottom. I can’t seem to figure out how to get them there.

<script>
    jQuery( document ).ready(function() {
       
        // Array of selectors
    // This is to initalize fancybox galleries to work on taxonomy groups.
        
        var selectorsArray = [];
        jQuery.each(taxo_data, function(key, value) {
            selectorsArray.push('[data-fancybox="' + value + '"]');
        });
        
        // Concatenate selectors into a single string
        var concatenatedSelectors = selectorsArray.join(',');


        jQuery(concatenatedSelectors).fancybox({
                
    caption : function( instance, item ) {
        var caption = jQuery(this).data('caption') || '';
                //console.log(caption);
        return caption;
    },
            baseTpl:
                '<div class="fancybox-container" role="dialog" tabindex="-1">' +
                '<div class="fancybox-bg"></div>' +
                '<div class="fancybox-inner">' +
                '<div class="fancybox-infobar"><span data-fancybox-index></span>&nbsp;/&nbsp;<span data-fancybox-count></span></div>' +
                '<div class="fancybox-toolbar">{{buttons}}</div>' +
                '<div class="fancybox-navigation">{{arrows}}</div>' +
                '<div class="fancybox-stage"></div>' +
                                '<div class="fancybox-for-titles"></div>' +
                '<div class="fancybox-caption"><div class=""fancybox-caption__body"></div></div>' +
                '</div>' +
                '</div>',
            thumbs: {
                autoStart: true,
                axis: 'x',
                openEffect  : 'none',
                closeEffect : 'none',
                prevEffect : 'none',
                nextEffect : 'none',
                closeBtn  : false,
                arrows    : false,
                nextClick : true,
                helpers : {
                    title : {
                        type : 'inside'
                    },
                    thumbs : {
                        width : 50,
                        height : 50,
                            tpl: function(thumb, index) {
                            return '<div class="fancybox-thumb-caption">' + thumb.opts.caption + '</div>';
                            }
                    }
                }
            },
            afterLoad: function(instance, current) {
                // Update the content of fancybox-for-titles with the caption
                console.log(current.opts.caption);
                jQuery('.fancybox-for-titles').html(current.opts.caption);
            }
        });

console.log('end');

    });

</script>

I am able to get the captions for the current gallery item, but not for all of them. And I tried to use the afterLoad function but that wasn’t working. I also tried to edit the tpl for the thumbs, but that didn’t do anything. When Fancybox creates the row of thumbnails, I’d also just like to include the caption.

Problem with HOC (Higher-Order Component) in React.js

This is my first question.
I am self-studying React.js, Node.js, and Express. For this reason, I am trying to create my own website where a user can register, log in, and access the page with their data only if the login is successful. My idea is to use the Higher Order Component (HOC) “Protect” that checks for successful authentication and, if it has occurred, loads “/ProtectedPage”. The problem I have is that the login is successful, and I receive the data correctly from the “/login” post request, but later, the authentication fails, and I don’t know why and how to resolve it. My idea is that the problem may be due to some error in the “Protected” components and their corresponding backend counterparts “verifyToken” and “/CheckAuth”.

You can view my code at this link: https://github.com/CiccioLagXCVIII/MyOwnSite.git

P.S. Clearly, I know that there are things to add (for example, ensuring that when the login form is submitted, the data is sent encrypted, performing checks, and other details), but if possible, I would like help with the problem I specified above because I would like to handle the other things on my own.

Thanks to anyone who will respond.

The control of the HOC component is not working, and the redirection after a successful login is not functioning correctly

Why is my website not working properly when I link a CSS file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Поле за адрес</title>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBeLekTr4uku8B4bp6hgRTSR3p0344esP0&libraries=places&callback=initAutocomplete" async defer></script>
    <script src="autocomplete.js" defer></script>
    <!-- <link rel="stylesheet" type="text/css" href="style.css"> -->
</head>
<body>
<div class="content">
    <h1>Въведете адрес</h1>
    <input id="autocomplete" placeholder="Въведете адрес" style="height: 50px; width: 600px; border-radius: 25px;" type="text" />
</div>
</body>

</html>
function initAutocomplete() {
  if (google && google.maps && google.maps.places) {
    let autocomplete = new google.maps.places.Autocomplete(
      document.getElementById('autocomplete'),
      {
        types: ['establishment'],
        componentRestrictions: {'country': ['BG']},
        fields: ['place_id', 'geometry', 'name']
      });
  } else {
    console.error('Google Maps API not loaded.');
  }
}

I want to create a website that autofills an adress when you start typing. I want to link an outside file for styling for my website but when I type <link rel="stylesheet" type="text/css" href="style.css"> in <head> the website stops working properly. Without the <link> everything works fine. I can style everything in the HTML file but to make the design adaptive I want to write it in its individual file. Is the problem in the script, the way I linked the scripts or something else and how do I fix it?

Why I can’t retrieve my mongodb collection on my domain while I am able to do it on my local

I am working on a Vuejs(v3) project. While I can retrieve the data from my Mongodb collection on my local I can’t do it for a specific domain name.

index.js file

const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const { v4: uuidv4 } = require('uuid')
const multer = require('multer')
require('dotenv').config({ path: '../.env' })

const app = express()
app.use(cors())

const CONNECTION_STRING = process.env.CONNECTION_STRING
const DATABASENAME = process.env.DATABASENAME

function find (name, query, response) {
  mongoose.connection.db.collection(name, function (err, collection) {
     collection.find(query).toArray((error, result) => {
      response.send(result)
    });
 });
}

app.listen(5038 || 3000, () => {
  mongoose
    .connect(CONNECTION_STRING, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      dbName: DATABASENAME,
    })
    .then(() => {
      console.log('Connected to the Database.')
    })
    .catch((err) => console.error(err))
})

app.get('/api/blogpage/getarticles', (request, response) => {
  find('articlescollection', {}, response)
})

I run axios.get("https://domainname/" + 'api/blogpage/getarticles')

and I see;

headers

Request URL:https://www.domainname/api/blogpage/getarticles
Request Method:GET
Status Code:200 OK

preview
We're sorry but mevn-app doesn't work properly without JavaScript enabled. Please enable it to continue.

response

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <link rel="icon" href="/favicon.ico">
        <title>mevn-app</title>
        <script defer="defer" src="/js/chunk-vendors.95815946.js"></script>
        <script defer="defer" src="/js/app.dfb1db13.js"></script>
        <link href="/css/chunk-vendors.ab6e52a4.css" rel="stylesheet">
        <link href="/css/app.897c0abf.css" rel="stylesheet">
    </head>
    <body>
        <noscript>
            <strong>We're sorry but mevn-app doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
        </noscript>
        <div id="app"></div>
    </body>
</html>

I tried various steps to solve but I couldn’t. Probably I am missing a point but I don’t know what is it…

Regex username javascript [duplicate]

I am trying to create a regex for the following:

Alphanumeric a-z, A-Z, 0-9
Special characters: @, _ and .

SPACES are NOT allowed

NOTE: The @ is optional and it can only be at the beginning

Valid examples:

@user_name
@user.name
user_name
user.name
.user.name_
_user.name_

INVALID examples:

user name
user:::name
user@name
user_$%$%name

here’s what I have so far:

/^[@]?[a-zA-Z0-9_.]*/

I don’t think it’s right because this is allowing me to include other special characters

How to disable double tap event on mobile for radio buttons?

Using a form with radio buttons. Works fine on the computer but fails on the mobile because I have to double-tap to select a radio button. Users will get confused.

How do I disable the double-tap requirement? I’ve checked a few other answers but they’re all using different code and I’m not sure how to apply it in my situation.

Any help is much appreciated.

Here’s what I’ve got so far:

<form><div class="monthly-box"><label for="monthly" class="container">
  <div class="monthly-header">Most Popular</div>
  <div class="monthly-body">
  <div class="monthly-input"><input type="radio" id="monthly" name="payment" value="monthly" checked="checked"><span class="checkmark-monthly-yearly"></span></div>
  <div class="monthly-text">
    <h2>Monthly Subscription - $79 USD <span style="color:#929292;font-weight: normal;"><s>$99</s></span></h2>
    <ul>
      <li>60 recorded audio lessons + live class on Zoom</li>
      <li>1-on-1 welcome call with the founder</li>
      <li>7-Day Free Trial + 90-Day Money Back Guarantee</li>
    </ul>
  </div>
  </div>
  </label>
  </div>
  
    <div class="yearly-box"><label for="yearly" class="container">
  <div class="yearly-header">Best Value</div>
  <div class="yearly-body">
  <div class="yearly-input"><input type="radio" id="yearly" name="payment" value="yearly">  <span class="checkmark-monthly-yearly"></span></div>
  <div class="yearly-text">
    <h2>Yearly Subscription - $474 USD <span style="color:#929292;font-weight: normal;"><s>$1,188</s></span></h2>
    <ul>
      <li>60 recorded audio lessons + live class on Zoom</li>
      <li>1-on-1 welcome call with the founder</li>
      <li>14-Day Free Trial + 90-Day Money Back Guarantee</li>
    </ul>
  </div>
  </div>
  </label>
  </div>
  
    <div class="onemonth-box"><label for="onemonth" class="container">
  <div class="onemonth-header"></div>
  <div class="onemonth-body">
  <div class="onemonth-input"><input type="radio" id="onemonth" name="payment" value="onemonth"><span class="checkmark-onemonth"></span></div>
  <div class="onemonth-text">
    <h2>Try One Month - $99 USD</h2>
  </div>
  </div>
  </label>
  </div>

</form>

<a href="" onclick='myFunction()' id="myLink">Checkout &#8594;</a>

</div>

<script>
    function myFunction() {
   
        if(document.getElementById('monthly').checked) {
            document.getElementById('myLink').href = "https://www.rageheart.co/beast-monthly";
        }
        if(document.getElementById('yearly').checked) {
            document.getElementById('myLink').href = "https://www.rageheart.co/beast-yearly";
        }
        if(document.getElementById('onemonth').checked) {
            document.getElementById('myLink').href = "https://www.rageheart.co/beast-1-month";
        }

    }
</script>

Handling Flickering with Theme Change and Local Storage in Next.js with Ant Design

I’m working on a feature for dynamically changing themes (light/dark) in a Next.js application using Ant Design. I’ve successfully implemented the theme switch
using a useState hook and a toggle switch. However, I’m struggling with storing the theme preference in local storage without causing a flicker on page load.

Here’s the relevant part of my layout.tsx:

"use client";

import { Layout, ConfigProvider, Switch, theme as antdTheme } from "antd";
import { useState } from "react";
const { Header, Content, Footer } = Layout;

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const [theme, setTheme] = useState<boolean>(false);

  const onChange = (checked: boolean) => {
    setTheme((prev) => !prev);
  };

  return (
    <ConfigProvider
      theme={{
        algorithm: theme ? antdTheme.darkAlgorithm : antdTheme.defaultAlgorithm,
      }}
    >
      <Layout>
        <Header></Header>
        <Content>
          <Switch defaultChecked onChange={onChange} />
          {children}
        </Content>
        <Footer>Footer</Footer>
      </Layout>
    </ConfigProvider>
  );
}

The switch works fine, but I’m unsure how to properly store and retrieve the theme setting from local storage.

Using useEffect to read the local storage value causes flickering on page load. To avoid this, I considered adding a conditional render like this:

const [mounted, setMounted] = useState(false);

useEffect(() => {
    setMounted(true);
});

return (
    {mounted && <ConfigProvider>...</ConfigProvider>}

However, conditioning the rendering of the main ConfigProvider node doesn’t seem like the best practice. Is there a more appropriate way to handle this scenario in a Next.js app? How can I effectively store and retrieve the theme setting from local storage without causing a flicker on page load?

Any suggestions or best practices for handling this issue would be greatly appreciated!