Is it good to use scoped style for iterated component in Vue

We use scoped style in component in Vue and it has advantages.
But suppose I have a component like BoxComponent.vue
and defined one class.

<style scoped>
.box-component{
  float: left;
  flex-grow: initial !important;
  margin: 0 3px;
}
</style>

I think it might be good to use this in one or twice but when I use this in loop maybe hundreds of loops, then It will generate independent style classes because vue-loader will treat each item differently.

In that case I think it could be problem in terms of speed and memory usuage.
Can anybody elaborate this please?
When it is good to use scoped style or global style in Vue.js?

How to init state for API server in NextJs

I am trying to have some instance loaded (run some init function) before my NextJs server can serve my API. For example:

// src/pages/api/getSelfCakeStats.ts
export default async function getSelfCakeStats(
  req: NextApiRequest,
  res: NextApiResponse
) {
  setChainId(ChainId.MAINNET); // <- I want to run this before the server is online
  initProvider();              // <- I want to run this before the server is online
...
}

It is doable Is there anyway I can do it explicitly in any given file of NextJs structure? the next.config.js is very limited in syntax so it is not an ideal place to run the logic while singleton pattern might do the job but it would get my instance to be intialized implicitly (init when null)

importing ConnectButton from web3uikit gives Error: Invalid hook call. Hooks can only be called inside of the body of a function component

I am using nextjs along with tailwind css and a bunch of other libraries like web3uikit.
the app work totally fine but as soon as I import ConnectButton from web3uikit and use it in the sidebar component, it gives me the following error:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

Here’s the link to the github repo, just cloning and install the dependencies would help you in setting up the project and then npm run dev.

Link: https://github.com/oneknucklehead/marketplace-web3

FirebaseError: Firebase: Error (auth/operation-not-allowed)

I have a problem like the below:

I want to solve this problem

 ```import app from './firebase.init';
    import { createUserWithEmailAndPassword, getAuth } from "firebase/auth";
    import { useState } from 'react';

    const auth = getAuth(app);

    function App() {
      const [email, setEmail] = useState('');
      const [password, setPassword] = useState('');

      const handleEmail = event => {
        setEmail(event.target.value);
      }

      const handlePassword = event => {
setPassword(event.target.value);

}

const formSubmit = event => {
createUserWithEmailAndPassword(auth, email, password)
.then( result =>{
const user = result.user;
console.log(user);
})
.catch(error =>{
console.error(error)
} )
event.preventDefault();
}

```

React.js private route related issue when trying to signup or login

I am getting this error “Cannot update a component (BrowserRouter) while rendering a different component (Login). To locate the bad setState() call inside Login” whenever I try to signUp or log in. I think this is occurring because of react router. But i couldn’t find where I messed up. Here is the code (index.js).

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<React.StrictMode>
<App />
</React.StrictMode>
</BrowserRouter>
 );
 reportWebVitals();

Here is App.js

import "./App.css";
import Header from "./Components/Shared/Header/Header";
import "bootstrap/dist/css/bootstrap.min.css";
import Footer from "./Components/Shared/Footer/Footer";
import { Route, Routes } from "react-router-dom";
import Home from "./Components/Pages/Home/Home";
import Login from "./Components/Pages/Login/Login";
import Register from "./Components/Pages/Login/Register";
import Contact from "./Components/Pages/Contact/Contact";
import NotFound from "./Components/Pages/NotFound/NotFound";
import Blogs from "./Components/Pages/Blogs/Blogs";
import Manage from "./Components/Pages/Manage/Manage";
import Add from "./Components/Pages/Add/Add";
import Myitems from "./Components/Pages/Myitems/Myitems";
import SingleInventory from "./Components/Pages/SingleInventory/SingleInventory";
import RequireAuth from "./Components/RequireAuth";

function App() {
return (
<div>
  <Header></Header>
  <Routes>
    <Route path="/" element={<Home></Home>}></Route>
    <Route
      path="/products/:id"
      element={
        <RequireAuth>
          <SingleInventory></SingleInventory>
        </RequireAuth>}
    ></Route>
    <Route path="/manage" element={<Manage></Manage>}></Route>
    <Route path="/add" element={<Add></Add>}></Route>
    <Route path="/myitems" element={<Myitems></Myitems>}></Route>
    <Route path="/blogs" element={<Blogs></Blogs>}></Route>
    <Route path="/contact" element={<Contact></Contact>}></Route>
    <Route path="/login" element={<Login></Login>}></Route>
    <Route path="/register" element={<Register></Register>}></Route>
    <Route path="*" element={<NotFound></NotFound>}></Route>
  </Routes>
  <Footer></Footer>
  </div>
     );
   }

export default App;

Here Login.js

import { Icon } from "@iconify/react";
import React, { useState } from "react";
import { Button, Form } from "react-bootstrap";
import {
useSignInWithEmailAndPassword,
useSignInWithFacebook,
useSignInWithGoogle,
}   from "react-firebase-hooks/auth";
import { Link, useLocation, useNavigate } from "react-router-dom";
import auth from "../../../firebase.init";
import logo from "../../../images/login.svg";

const Login = () => {
const navigate = useNavigate();
const location = useLocation();

const from = location.state?.from?.pathname || "/";


const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [signInWithEmailAndPassword, user, loading, error] =
useSignInWithEmailAndPassword(auth);

const [signInWithGoogle, gUser, gLoading, gError] = useSignInWithGoogle(auth);
const [signInWithFacebook, fbUser, fbLoading, fbError] =
useSignInWithFacebook(auth);

const handleFormSubmit = (e) => {
e.preventDefault();
signInWithEmailAndPassword(email, password);
};

 const handleGoogleLogin = () => {
   signInWithGoogle();
  };
 const handleFbLogin = () => {
  signInWithFacebook();
 };
 if (user || fbUser|| gUser) {
 navigate(from, { replace: true });
 }
 return (
 <div style={{ minHeight: "100vh" }} className="d-flex">
  <div className="w-50 border border-1 d-flex align-items-center justify-content-center bg- 
  warning">
    <img className="w-50" src={logo} alt=""/>
  </div>
  <div className="w-50 d-flex align-items-center justify-content-center ">
    <div className="w-75 border border-1 p-5">
      <h1 className="d-inline-block pb-2 mb-4 border-1 border-dark border-bottom">
        Log in
      </h1>
      <Form className=" mx-auto" onSubmit={handleFormSubmit}>
        <Form.Group className="mb-3" controlId="formBasicEmail">
          <Form.Label>Email address</Form.Label>
          <Form.Control
            type="email"
            name="email"
            placeholder="Enter email"
            onBlur={(e)=>setEmail(e.target.value)}
          />
        </Form.Group>

        <Form.Group className="mb-3" controlId="formBasicPassword">
          <Form.Label>Password</Form.Label>
          <Form.Control
            type="password"
            name="password"
            placeholder="Password"
            onBlur={(e)=>setPassword(e.target.value)}
          />
        </Form.Group>
        <p className="text-end">Forget password</p>
        <Button className="w-100" variant="primary" type="submit">
          Log in
        </Button>
      </Form>
      <p className="text-center">
        Don't have an account?
        <Link className="text-decoration-none" to="/register">
          Sign Up
        </Link>
      </p>
      <div className="text-center ">
        <Icon onClick={handleGoogleLogin} icon="logos:google-icon" />
        <Icon
          onClick={handleFbLogin}
          className="text-primary"
          icon="fa6-brands:facebook"
        />
        <Icon icon="logos:github-icon" />
      </div>
    </div>
  </div>
</div>
     );
  };

  export default Login;

Retrieve email and phone for billing in applepay js

I am using ApplePay Web integration via JS API. Wanted to know if there was any way to fetch user’s email address associated with apple pay account. I need it for billing processing.

I had tried below but getting empty string –

requiredBillingContactFields: [
        'phone',
        'email'                 
]

Any help?

Using recursion to weave js [duplicate]

We are given the following class


class Queue{

    constructor(){
        this.data=[];
    }

    add(record){
        this.data.unshift(record)
    }
    remove(){
        return this.data.pop()
    }
    peek(){
        // console.log()
        let lastElement=this.data[this.data.length-1]
        return lastElement;
     } 
}

without using any array features, we are required to write a weave function which will add elements alternatively as shown below
enter image description here

The function looks like this (ie takes two arguments/queues as below)

function weave(sourceOne, sourceTwo) {}

I would like to know if we can solve this using recursion(not a while loop), the code I have written so far doesnt
work as it initiates the new queue everytime the function is called ,


 let track =0

function weave(sourceOne, sourceTwo) {

    if(track>0){
        const q3 = new Queue()
    }
   track++

    //in simple language
  
    //while sourceOne.peek() is true keep adding
    
   
    if(sourceOne.peek()){
        q3.add(sourceOne.remove())
    }
    if(sourceTwo.peek()){
        q3.add(sourceTwo.remove())
    }
 
    console.log(q3)

   if (sourceTwo.peek()|| sourceOne.peek()){
       weave(sourceOne,sourceTwo)
   }
   
   else if( sourceTwo.peek()== null && sourceOne.peek()==null){
     
    return q3
   }
      
   }

The error is given below, thanks for any help !

enter image description here

Best way to implement a library

I have created a library, for the sake of learning, with a few method in the Global Object, Global Function Object and the Global Array Object, apart from my own Object created inside the library.

I have created the library inside a IIFE and then passed the arguments.

The methods are simulating basically other built-in methods but with my own logic just for learning purposes

The library with few examples is the following.

”’

(function (global, globalObj, globalArr, globalFunc) {

globalArr.prototype.forEach1 = function (fun) {
    self = this;
    for (let value of self) {
        fun(value);
    }
};

globalFunc.prototype.bind2 = function(context, ...a) {
    return (...b) => this.call(context, ...a, ...b);
};

globalFunc.prototype.call2 = function(context, ...a) {
    if (typeof context === "object") {
        let bound = Symbol();
        context[bound] = this;
        console.log(this);
        let result = context[bound](...a);
        delete context[bound];
        return result;
    };
    return this(...a);
};

myL.keys1 = function(obj) {
    let keys = [];  
    for (let key in obj) {
        if (obj.propertyIsEnumerable(key)) {
            keys.push(key);
        }
    }
    return keys;
};

myL.values1 = function(obj) {
    let values = [];
    let keys = myL.keys1(obj);
    for (let key of keys) {
        values.push1(obj[key]);
    }
    return values;
};

myL.instanceOf1 = function(obj, target) {
    return obj.constructor == target.prototype.constructor;
};

myL.about = function(obj) {
    let keys = M$.keys1(obj);
    let values = M$.values1(obj);
    let prot = obj.__proto__;
    let constr = obj.constructor;
    for (i=0; i < keys.length; i++) {
        console.log(`Property ${i+1} and value:n${keys[i]}: ${values[i]}.`);
    };  
    console.log(`Object prototype is: ${prot}.`)
    console.log(`Object constructor is: ${constr}.`)
};

global.myL = global.M$ = myL;

}(window, Object, Array, Function));

”’

As you can see I have created method for Array.prototype, Function.prototype, Object.prototype and myL (my library).

Is this way the best one to create a library so anyone could use it outside?

I have tried it and I could actualy use all the methods created and I had no interference with the variables and methods, but I am probably missing lots of things here.

Thank you !!

Sending images from React passes an empty array to NodeJS using DragAndDrop

I have searched for a lot of information on how to upload images as well as information on different inputs, but I cannot understand why the images are not received in NodeJS.

I have a form, in this I have different unputs but to load images I am using react-dropzone, the images that are inside react-dropzone are saved in the state correctly as follows:

DragDrop component

const DragAndDrop = ({files, setFiles, setDropError }) => {
  const onDropRejected = () => {
    setDropError('Imágenes con tamaño Máximo de 1MB')
    setTimeout(() => {
      setDropError('')
    }, 3000)
  }

  const {
    acceptedFiles,
    fileRejections,
    getRootProps,
    getInputProps
  } = useDropzone({  
    accept: {
      'image/jpeg': [],
      'image/jpg': [],
      'image/png': []
    },  
    maxFiles:3,
    maxSize:1000000,
    onDropRejected,
    onDropAccepted: acceptedFiles => {
     setFiles(acceptedFiles.map(file => 
      Object.assign(file, {
        preview: URL.createObjectURL(file)
      }))); 
    }
  })

  const removeFile = file => () => {
    const newFiles = [...files]
    newFiles.splice(newFiles.indexOf(file), 1)
    setFiles(newFiles)
  }

  const removeAll = () => {
    setFiles([])
  }

  const thumbs = files.map(file => (

      <div key={file.name}>
        <button onClick={removeFile(file)} className="text-center hover:bg-blue-200 absolute rounded">
          <span className='p-2 text-center text-lg'>x</span>
        </button>
        <div className='w-32'>
          <img
            src={file.preview}
            // Revoke data uri after image is loaded
            onLoad={() => { URL.revokeObjectURL(file.preview) }}
          />
        </div>
      </div>
  ))

  useEffect(() => {
    // Make sure to revoke the data uris to avoid memory leaks, will run on unmount
    return () => files.forEach(file => URL.revokeObjectURL(file.preview));
  }, []);

  const acceptedFileItems = acceptedFiles.map(file => (
    <li key={file.path}>
      {file.path} - {file.size} bytes
    </li>
  ));

  const fileRejectionItems = fileRejections.map(({ file, errors  }) => { 
   return (
     <li key={file.path}>
          {file.path} - {file.size} bytes
          <ul>
            {errors.map(e => <li key={e.code}>{e.message}</li>)}
         </ul>
     </li>
   ) 
  });
  

  return (
    <section className={`container mt-6`}>
      <div {...getRootProps({ className: 'dropzone' })} className={`flex flex-col justify-center border-2 border-cyan-600 border-dashed p-4 cursor-pointer  ${ files.length === 3 && 'pointer-events-none' }`}>
        <input {...getInputProps()} />
        <div className='flex flex-col justify-center text-center gap-2 mb-2'>
          <p>Arrastra y suelta imágenes o selecciona dando click</p>
          <em className='text-xs'>(Máximo 3 imágenes, .jpg, .png)</em>
        </div>
      </div>
      <aside className='text-xs mt-4'>
      {files.length === 3 && <div>{files.length}</div>}
    {/*     <h4>Archivos Correctos</h4>
        <ul>{acceptedFileItems}</ul>
        <h4>Archivos con error</h4>
        <ul>{fileRejectionItems}</ul> */}
        <div className="flex gap-4 justify-center">
          {thumbs}
        </div>
      </aside>
      {files.length > 0 && <button onClick={removeAll} className="btn btn-xs text-xs mt-4 btn-ghost">Eliminar</button>}
    </section>
  );
}

export default DragAndDrop

After imported inside the component where I have the form I show it correctly and the user can choose up to 3 images:

const NewProduct = () => {
 const [files, setFiles] = useState([])

 const onSubmit = data => {
  try {
    data.pictures = files // Here I indicate that data.pictures will be equal to the content of my state files
    postProduct(data)
  } catch (error) {
  }
}
return (

            <form 
                onSubmit={handleSubmit(onSubmit)}
                className='flex-auto px-4 rounded-b-md md:px-10 py-5 pt-0 border-2 bg-slate-100  shadow-lg'
              >
                   <DragAndDrop
                      files={files}
                      setFiles={setFiles}
                      setDropError={setDropError}
                    />

----

So this is sent to make the request from postProduct to Nodejs:

Log of the data that is sent to the server

Now, to make the request to NodeJS, I use postProduct, where I pass the form data that already contains the images in data.pictures and use FormData traversing the array of images and setting ‘pictures’

    const postProduct = async product => { 

        try {
           
            const dataOnLs = localStorage.getItem('cmtjs')
            const formData = new FormData()

            for (let i = 0; i < product.pictures.length; i++) {
                formData.append(`pictures`, product.pictures)
            }

            formData.append('barCode', product.barCode)
            formData.append('idProduct', product.idProduct)
            formData.append('desc', product.desc)
            formData.append('name', product.name)
            formData.append('category', product.category)
            formData.append('presentation', product.presentation)
            formData.append('provider', product.provider)
            formData.append('purchasePrice', product.purchasePrice)
            formData.append('salePrice', product.salePrice)

            const config = {
                headers: {
                    "Content-Type": "multipart/form-data",
                    apiKey: dataOnLs
                }      
            } 

            const { data } = await axiosClient.post(`/products`, formData, config )

But when doing a console.log(req.files) from Nodejs it always indicates an empty array.

empty array from nodejs

Within POstProduct I have printed the content of formData in the console and despite the fact that it throws me the ‘pictures’ key, its value is [object File] but in NodeJS it arrives empty:

            const formData = new FormData()

            for (let i = 0; i < product.pictures.length; i++) {
                formData.append(`pictures`, product.pictures)
            }

            for (var d of formData.entries()) {
                console.log(d); 
            }

formData Pictures log

So the texts of the form are sent correctly to NodeJS but the images are always received as an empty array. I don’t really understand what’s just going on.

Uncaught ReferenceError: require is not defined in browser

when i run the js file where this function is written it works and show data in the console. but when i run it in a browser from the html file with onclick i get the error: Uncaught ReferenceError: require is not defined
i tried using the function in tag but didn’t work

function appendData() {
  const data = require("../assets/Data/Courses.json");
    
  var length = Object.keys(data.employees).length;
    var Text = new Array();
    for(let i = 0; i < length; i++) 
    {
        //document.getElementById('test').innerHTML += "<br>"+data.employees[i].firstName + " " + data.employees[i].lastName ;
        Text[i] = data.employees[i].firstName+ " " + data.employees[i].lastName ;
        console.log(Text[i]);
    } 
}

How do I set a header in the login route so the browser remembers who is logged in

I’ve created a user login back end and everything works fine, but when I log in to a user detail, despite being correct, I’m unable to explore other routes because the user isn’t authorized. how do I save the access token to the browser so it remembers? This is the login route below.

router.post("/login", async (req, res) => {
try {
    const oneUser = await users.findOne({
        username: req.body.username,
    });

    if (!oneUser) {
        return res.status(500).json("User is not in the database");
    }

    const oPassword = cj.AES.decrypt(
        oneUser.password,
        process.env.pass
    ).toString(cj.enc.Utf8);

    if (oPassword !== req.body.password) {
        return res.status(500).json("Password is incorrect");
    }

    const accessToken = jwt.sign(
        {
            id: oneUser._id,
            isAdmin: oneUser.isAdmin,
        },
        process.env.jwtToken,
        { expiresIn: "300" }
    );

    const { password, ...others } = oneUser._doc;
    res.status(200).json({ ...others, accessToken });

} catch (err) {
    res.status(500).json(err);
}

});

I saw something like this on the net.

res.header("token", accessToken)