Why is text typing effect not working using GSAP?

GSAP TextPlugin not working

Problem

  • html
<body>
    <section class="hero">
        <h1></h1>
    </section>
    ..... more html
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.3/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.4/TextPlugin.min.js"></script>

html-img

  • js
gsap.registerPlugin(TextPlugin)
var master_tl = gsap.timeline();
master_tl.add(loading())
master_tl.add(heroAnimateIn())

// .... more js

function heroAnimateIn() {
    let tl = gsap.timeline();
    // tl.registerPlugin(TextPlugin);
    tl.to('h1', {duration: 2, text: "Hello World!", ease: "none"})
    return tl
}
  • The h1 remains empty after the js runs.

What I want?

I want the tying effect like shown here codepen source

Note

  • I am new to gsap.
  • If any more information needed please tell in comments.

Nest js npm run start failing

I have installed fresh Nest js on new EC2 machine but when I am running it for the very first time it gives following error (looks like npm install fails abrubtly whithout any visible error) :

ubuntu@ip-172-31-15-190:~/projects/mynestjs$ npm run start:dev

> [email protected] start:dev
> nest start --watch

node:internal/modules/cjs/loader:1144
  const err = new Error(message);
              ^

Error: Cannot find module '/home/ubuntu/projects/mynestjs/node_modules/@nestjs/cli/commands'
Require stack:
- /home/ubuntu/.nvm/versions/node/v20.10.0/lib/node_modules/@nestjs/cli/lib/utils/local-binaries.js
- /home/ubuntu/.nvm/versions/node/v20.10.0/lib/node_modules/@nestjs/cli/bin/nest.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1144:15)
    at Module._load (node:internal/modules/cjs/loader:985:27)
    at Module.require (node:internal/modules/cjs/loader:1235:19)
    at require (node:internal/modules/helpers:176:18)
    at loadLocalBinCommandLoader (/home/ubuntu/.nvm/versions/node/v20.10.0/lib/node_modules/@nestjs/cli/lib/utils/local-binaries.js:13:26)
    at bootstrap (/home/ubuntu/.nvm/versions/node/v20.10.0/lib/node_modules/@nestjs/cli/bin/nest.js:14:83)
    at Object.<anonymous> (/home/ubuntu/.nvm/versions/node/v20.10.0/lib/node_modules/@nestjs/cli/bin/nest.js:25:1)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/home/ubuntu/.nvm/versions/node/v20.10.0/lib/node_modules/@nestjs/cli/lib/utils/local-binaries.js',
    '/home/ubuntu/.nvm/versions/node/v20.10.0/lib/node_modules/@nestjs/cli/bin/nest.js'
  ]
}

Node.js v20.10.0
ubuntu@ip-172-31-15-190:~/projects/mynestjs$

It does not work with npm run start and npm run start:dev both.

While installing npm install --silent failed without any error.

I also checked and found that package-lock.json has not been generated.

Node js version is v20.10.0

NPM version is 10.2.5

nest -v command returns error even though I had installed nest globally.

My package.json is as follows:

{
  "name": "mynestjs",
  "version": "0.0.1",
  "description": "",
  "author": "",
  "private": true,
  "license": "UNLICENSED",
  "scripts": {
    "build": "nest build",
    "format": "prettier --write "src/**/*.ts" "test/**/*.ts"",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",
    "lint": "eslint "{src,apps,libs,test}/**/*.ts" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  },
  "dependencies": {
    "@nestjs/common": "^10.0.0",
    "@nestjs/core": "^10.0.0",
    "@nestjs/platform-express": "^10.0.0",
    "reflect-metadata": "^0.1.13",
    "rxjs": "^7.8.1"
  },
  "devDependencies": {
    "@nestjs/cli": "^10.0.0",
    "@nestjs/schematics": "^10.0.0",
    "@nestjs/testing": "^10.0.0",
    "@types/express": "^4.17.17",
    "@types/jest": "^29.5.2",
    "@types/node": "^20.3.1",
    "@types/supertest": "^2.0.12",
    "@typescript-eslint/eslint-plugin": "^6.0.0",
    "@typescript-eslint/parser": "^6.0.0",
    "eslint": "^8.42.0",
    "eslint-config-prettier": "^9.0.0",
    "eslint-plugin-prettier": "^5.0.0",
    "jest": "^29.5.0",
    "prettier": "^3.0.0",
    "source-map-support": "^0.5.21",
    "supertest": "^6.3.3",
    "ts-jest": "^29.1.0",
    "ts-loader": "^9.4.3",
    "ts-node": "^10.9.1",
    "tsconfig-paths": "^4.2.0",
    "typescript": "^5.1.3"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".*\.spec\.ts$",
    "transform": {
      "^.+\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
}

pass a value from component to component react

I have some code on react that uses two independent components. On clicking a button in the first component, I hide the current component and display the other component. But also, I want to pass some values from the first component (from INPUTS) to the second component. Can you please tell me how can I do that? Here is the code:

App.js

import React from 'react';
import { useState } from 'react';
import { FirstSection} from './components/FirstSection';
import { SecondSection} from './components/SecondSection';

function App() {
  const [checkSection, setSection] = useState(false);
  const showSecondSection= () => setSection(true);
  
  return (
    <div className="App">
        {checkSection ? <SecondSection /> : <FirstSection onClick={showSecondSection} />}
    </div>
  );
}

export default App;

FirstSection.jsx

import { useState } from 'react';

export function FirstSection({onClick}) {
    const [Value, setValue] = useState();
    return(
        <>
         <input type="text" value="{input1}" />
         <input type="text" value="{input2}" />
         <button onClick={onClick}>Continue</button>
        </>
    )
}

SecondSection.jsx

export function SecondSection() {
    return(
        <>
         <p>{input1}, {input2}</p> <== here I want to pass data from the first component
        </>
    )
}

why is schad cn not installing although i have done everything according to their documentation?

i followed the documentation of schadcn and did everything correctly . I installed nextjs with typescript and tailwind css.
My next version is 14.0.4
My node js version is 20.10.0
Once i write this in my terminal (npx shadcn-ui@latest init),
It shows me this(‘shadcn-ui’ is not recognized as an internal or external command,
operable program or batch file.)
can anyone help?

Web App navigation using keyboard control in 2023? [closed]

I’m wondering if there is an out of the box solution to implement navigation in a web application using keyboard controls, especially arrow keys to move across the elements on the page in desired configuration.

I found that there is a specification https://www.w3.org/TR/2021/WD-css-ui-4-20210316/#keyboard
that describes desired functionality, but it’s a draft on latest update.

Example from the specification

button#b1 {
  top:0; left:50%;
  nav-right:#b2; nav-left:#b4;
  nav-down:#b2; nav-up:#b4;
}

button#b2 {
  top:50%; left:100%;
  nav-right:#b3; nav-left:#b1;
  nav-down:#b3; nav-up:#b1;
}

Question is, are there any existing libraries that provide similar api to customize the navigation using keyboard? Maybe there good alternatives using javascript or hyperscript?

I want apply that to a form, where user can navigate across inputs, here is the example

<form style="padding-top: 4em"
          hx-post="/todo"
          hx-target="#todo-grid"
          hx-swap="beforeend"
          hx-headers='{"{inject:csrf.headerName}":"{inject:csrf.token}"}'>
        <div class="f-row packed">
            <div class="f-col flex-grow:6">
                <label class="allcaps" for="title">title</label>
                <input type=text id="title" name="title">
            </div>
            <div class="f-col flex-grow:3">
                <label class="allcaps" for="start">start</label>
                <input type=date id="start" name="start">
            </div>
            <div class="f-col flex-grow:3">
                <label class="allcaps" for="target">finish</label>
                <input type=date id="target" name="target">
            </div>
        </div>
        <div class="f-row packed">
            <div class="f-col flex-grow:12">
                <label class="allcaps" for="description">description</label>
                <input type=text id="description" name="description">
            </div>
        </div>
        <div class="f-row" style="padding-top: 1rem">
            <button class="button big color ok" type="submit">SUBMIT</button>
        </div>
    </form>

And something that I wish can be real one day

#title {
    nav-right: #start;
    nav-down: #description;
}
#start {
    nav-right: #target;
    nav-left: #title;
    nav-down: #description;
}
#target {
    nav-left: #start;
    nav-down: #description;
}
#description {
    nav-up: #start;
}

How to live stream to youtube using Agora?

I have a use case in which I start live streaming using Agora on a web app and now have to extend it to other platforms like youtube, facebook, twitch etc. Is there a way to do that directly? If not, any suggestions how it can be done using a custom approach. Thanks!

MongoServerError trying to join two different conditions

I want to execute a MongoDB query using Javascript. More in detail, I want to return documents based on two different conditions.

The first one is shown here:

        $or: [
          { "users.username": user.username },
          { buyer: user.username }
        ]

The second one is:

$or: [
          { description: { $regex: req.query.q } },
          { buyer: { $regex: req.query.q } },
          { category: { $regex: req.query.q } }
        ]

Joining the two conditions in a single query, the one that I have is the following:

const expenses = await db
    .collection("expenses")
    .find({
      $expr: {
        $or: [
          { "users.username": user.username },
          { buyer: user.username }
        ]
      },
      $expr: {
        $or: [
          { description: { $regex: req.query.q } },
          { buyer: { $regex: req.query.q } },
          { category: { $regex: req.query.q } }
        ],
      },
    })

When I execute it, I obtain the following error:

MongoServerError: Unrecognized expression '$regex'

What can I do to solve the error?
Thank you in advance for your patience.

Problem with backend request, after creating the build

In short, during development, the backend worked normally, I could register, search for users, and so on. But when I created a build and sent it to hosting, I can’t register and perform operations with the backend because an error appears. I will provide my code to understand the situation.

Here is the error:
RegisterPage.jsx:46
POST https://famfindtree.com/register 404 (Not Found)

Here are the files:
server.js:

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt');
const cors = require('cors'); // Import cors module

const app = express();
const PORT = process.env.PORT || 4000;

// Connect to MongoDB (replace 'your_mongodb_uri' with your URI)

// User model for MongoDB
const User = mongoose.model('User', {
    username: String,
    email: String,
    password: String,
});

app.use(cors()); // Use cors middleware
app.use(bodyParser.json());

// Handle user registration
app.post('/register', async (req, res) => {
    try {
        console.log('Received data:', req.body);

        const { username, email, password } = req.body;

        // Check if the user with the same email already exists
        const existingUser = await User.findOne({ email });
        if (existingUser) {
            return res.status(400).json({ error: 'User with this email already exists' });
        }

        // Hash the password before saving it to the database
        const hashedPassword = await bcrypt.hash(password, 10);

        // Create a new user with the hashed password
        const newUser = new User({ username, email, password: hashedPassword });
        await newUser.save();

        res.status(201).json({ message: 'User registered successfully' });
    } catch (error) {
        console.error('Error during registration:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});
// Handle user login
app.post('/login', async (req, res) => {
    try {
        const { email, password } = req.body;

        // Find the user with the provided email
        const user = await User.findOne({ email });

        // If the user is not found, return an error
        if (!user) {
            return res.status(401).json({ error: 'Invalid email or password' });
        }

        // Compare the provided password with the hashed password in the database
        const passwordMatch = await bcrypt.compare(password, user.password);

        // If passwords match, login is successful
        if (passwordMatch) {
            return res.status(200).json({ userId: user._id });
        } else {
            return res.status(401).json({ error: 'Invalid email or password' });
        }
    } catch (error) {
        console.error('Error during login:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});
// Handle search
app.post('/search', async (req, res) => {
    try {
        const { username} = req.body;

        // Build the search query based on the provided criteria
        const searchQuery = {
            username: new RegExp(username, 'i'),
          
        };

        // Execute the search in the MongoDB database
        const results = await User.find(searchQuery);

        res.status(200).json(results);
    } catch (error) {
        console.error('Error during search:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});




app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

register.jsx:

import React, { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { v4 as uuidv4 } from 'uuid';
import '../styles/RegisterPage.css';

function RegisterPage() {
    const navigate = useNavigate();
    const [formData, setFormData] = useState({
        username: '',
        email: '',
        password: '',
    });
    const [formErrors, setFormErrors] = useState({});

    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setFormData({ ...formData, [name]: value });
    };

    const validateForm = () => {
        const errors = {};
        if (formData.username.trim() === '') {
            errors.username = 'Username is required';
        }
        if (formData.email.trim() === '') {
            errors.email = 'Email address is required';
        }
        if (formData.password.trim() === '') {
            errors.password = 'Password is required';
        }
        if (formData.confirmPassword !== formData.password) {
            errors.confirmPassword = 'Passwords do not match';
        }
        setFormErrors(errors);
        return Object.keys(errors).length === 0;
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        const isFormValid = validateForm();

        const uuid = uuidv4();

if (isFormValid) {
    try {
        const response = await fetch('https://famfindtree.com/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ ...formData, uuid }), 
        });
        
        
            

        if (response.ok) {
            const responseData = await response.json();
            const userId = responseData.userId; 
            localStorage.setItem('authToken', userId);
            navigate('/');
        } else {
            const errorData = await response.json();
            console.error('Registration failed:', errorData.error);
        }
    } catch (error) {
        console.error('Error during registration:', error);
    }
}
    };



    return (
        <div>
            <section>
                <div className='container-pc-ver'>
                    <div className='register-decorative-image'></div>
                    <div className='container-sign-up'>
                        <div className='register-content'>
                            <div className='logo-register'>
                                <svg xmlns="http://www.w3.org/2000/svg" width="25" height="24" viewBox="0 0 25 24" fill="none">
                            <g clip-path="url(#clip0_3314_1044)">
                                <path d="M24.5 3.253C24.4818 4.4821 24.3727 5.70807 24.1736 6.92054C24.1304 7.20829 24.0776 7.49116 24.0248 7.76915C22.8664 6.93976 21.6241 6.23837 20.3192 5.6769C19.1422 5.16742 17.9187 4.77699 16.6664 4.51128C16.5875 4.48985 16.5073 4.47356 16.4264 4.46251C15.1622 4.20355 13.876 4.07124 12.5864 4.06747H12.4712C11.1816 4.07124 9.89541 4.20355 8.6312 4.46251C8.55026 4.47356 8.4701 4.48985 8.3912 4.51128C7.13888 4.77699 5.91537 5.16742 4.7384 5.6769C3.41518 6.23493 2.15509 6.93641 0.98 7.76915C0.9272 7.49116 0.8744 7.20829 0.8312 6.92054C0.630492 5.70819 0.51978 4.48222 0.5 3.253C1.69826 2.54789 2.95411 1.94905 4.2536 1.46312L4.5464 1.35582C5.71175 0.937102 6.90734 0.610984 8.1224 0.38041C8.3096 0.341394 8.5016 0.312132 8.6936 0.282869C9.84034 0.101731 10.9987 0.00718229 12.1592 0L12.8312 0C13.9922 0.0136361 15.1505 0.114706 16.2968 0.302378C16.4888 0.33164 16.6808 0.360902 16.868 0.399919C18.0831 0.630492 19.2787 0.95661 20.444 1.37533L20.7368 1.48263C22.0389 1.96177 23.298 2.55409 24.5 3.253Z" fill="#5757FF"/>
                                <path d="M19.3449 9.69055C18.9412 10.8435 18.4351 11.9568 17.8329 13.0167L17.6313 13.363C16.3554 12.7487 14.9819 12.3705 13.5753 12.2461C13.2181 12.2087 12.8592 12.1908 12.5001 12.1925C12.1401 12.1925 11.7801 12.1925 11.4249 12.2413C10.0164 12.3665 8.64118 12.7464 7.3641 13.363C7.98645 14.4119 8.70139 15.4011 9.5001 16.3185C9.6153 16.455 9.7353 16.5867 9.8553 16.7184C10.6639 17.6094 11.549 18.4255 12.5001 19.1569C13.6428 20.0275 14.8738 20.7714 16.1721 21.376C15.9849 21.5369 15.8025 21.693 15.6105 21.8637C14.6315 22.659 13.5914 23.3733 12.5001 23.9998C11.4077 23.3624 10.3675 22.6366 9.3897 21.8295C9.1977 21.6735 9.0153 21.5174 8.8281 21.3418C8.00072 20.6214 7.2214 19.8459 6.4953 19.0204C6.2649 18.757 6.0153 18.4888 5.8233 18.2156C5.18823 17.4193 4.60461 16.5819 4.0761 15.7088C3.8697 15.3772 3.6729 15.0358 3.4857 14.6895C3.00373 13.8034 2.57573 12.888 2.2041 11.9486C4.28551 10.1687 6.78072 8.95986 9.4521 8.43715C10.0642 8.31515 10.6829 8.23046 11.3049 8.18354C11.6985 8.15428 12.0969 8.13965 12.4953 8.13965C12.8937 8.13965 13.2921 8.13965 13.6857 8.18354C15.6471 8.33551 17.5649 8.8495 19.3449 9.70031V9.69055Z" fill="#5757FF"/>
                            </g>
                            <defs>
                                <clipPath id="clip0_3314_1044">
                                <rect width="24" height="24" fill="white" transform="translate(0.5)"/>
                                </clipPath>
                            </defs>
                        </svg>
                            </div>
                            <div className='container-title-register'>
                                <h1 className='title-register'>Create an account</h1>
                            </div>
                            <div className='container-register-txt'>
                                <p className='register-txt'>Let’s get started with your 30-day free trial.</p>
                            </div>
                            <div className='container-register-form'>
                                <form
                                    id="registrationForm"
                                    onSubmit={handleSubmit}
                                    action="/register"
                                    method='POST'
                                    className='register-form'
                                >
                                    <label htmlFor="username" className='register-label'>Login</label>
                                    <br />
                                    <input
                                        type="text"
                                        className='register-inputs'
                                        id="username"
                                        name="username"
                                        placeholder='Enter Login'
                                        required
                                        value={formData.username}
                                        onChange={handleInputChange}
                                    />
                                    {formErrors.username && <p className="error-message">{formErrors.username}</p>}
                                    <br />
                                    <label htmlFor="email" className='register-label'>Email address</label>
                                    <br />
                                    <input
                                        type="email"
                                        className='register-inputs'
                                        id="email"
                                        name="email"
                                        placeholder='Enter Email'
                                        required
                                        value={formData.email}
                                        onChange={handleInputChange}
                                    />
                                    {formErrors.email && <p className="error-message">{formErrors.email}</p>}
                                    <br />
                                    <label htmlFor="password" className='register-label'>Password</label>
                                    <br />
                                    <input
                                        type="password"
                                        className='register-inputs'
                                        id="password"
                                        name="password"
                                        placeholder='Enter Password'
                                        required
                                        value={formData.password}
                                        onChange={handleInputChange}
                                    />
                                    {formErrors.password && <p className="error-message">{formErrors.password}</p>}
                                    <br />
                                    <label htmlFor="confirm-password" className='register-label'>Repeat Password</label>
                                    <br />
                                    <input
                                        type="password"
                                        className='register-inputs'
                                        id="confirm-password"
                                        name="confirmPassword"
                                        placeholder='Repeat Password'
                                        required
                                        onChange={handleInputChange}
                                    />
                                    {formErrors.confirmPassword && <p className="error-message">{formErrors.confirmPassword}</p>}
                                    <br />
                                    <button type="submit" className='register-btn'>Create Account</button>
                                </form>
                                <div className='container-register-txt'>
                                    <p className='register-txt-login'>
                                        Already have an account?
                                        <Link to="/sign-in" className='register-link-to-login'>Log in</Link>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    );
}

export default RegisterPage;

I think the problem is either in the connection of the server part, or a problem with the port. By the way, I use A2 Hosting.

Using Props to Set Initial Value of VueMultiselect inside a Modal in Vue3

I’m developing an app where I have a value from the parent file passed as a prop to the child file which is then used to set the default value of a VueMultiselect. It seems like I can access the prop without issues in the child file within the template or in functions I create in the script, however, I get null values when trying to access the prop outside of either of the two contexts I mentioned earlier. The expected behavior is that the VueMultiselect has a default letter (from A to D) that is preselected based on the prop by the time that the modal is opened, but nothing is chosen when I actually do so. Please see the code below, thank you!

App.vue

<template>
  <div>
    <button
      type="button"
      class="btn btn-outline-primary"
      data-bs-target="#resultModal"
      data-bs-toggle="modal"
    >
    Click Me!
    </button>
    <Test :letter="letter" />
  </div>
</template>

<script>
import Test from './components/Test.vue'

export default {
  name: 'app',
  components: {
    Test
  },
  mounted(){
      console.log(this.generateRandomLetter());
      this.letter = this.generateRandomLetter();
    },
  data() {
    return {
      letter: ''
    };
  },
  methods: {
    generateRandomLetter() {
      // Generate a random number between 0 and 3 (inclusive)
      const randomNumber = Math.floor(Math.random() * 4);

      // Convert the random number to a letter between A and D
      const randomLetter = String.fromCharCode('A'.charCodeAt(0) + randomNumber);

      return randomLetter;
    }
  }
}
</script>

<style scoped>
button {
  background: #26E6A4;
  border: 0;
  font-size: 16px;
  color: '#fff';
  padding: 10px;
  margin-left: 28px;
}
</style>

Test.vue

<template>
  <div
    class="modal fade"
    id="resultModal"
    tabindex="-1"
    role="dialog"
    aria-labelledby="resultModalLabel"
  >
  <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
    <div class="modal-dialog">
    <div class="modal-content p-3">
    <VueMultiselect
            v-model="selectedLetter"
            :options="dataSet"
            :close-on-select="true"
            :show-labels="false"
            :searchable="false"
            placeholder="Select a letter"
    >
    </VueMultiselect>
    </div>
    </div>
    </div>
    </div>
  </template>
  
  <script>
  import VueMultiselect from 'vue-multiselect';
  import { ref } from 'vue';
  
  export default {
    name: 'Test',
    components: {
      VueMultiselect
    },
    props: ['letter'],
    setup(props) {
      const selectedLetter = ref(props.letter);
      console.log(selectedLetter.value);
  
      return {
        selectedLetter,
        dataSet: ['A', 'B', 'C', 'D']
      };
    }
  };
  </script>

  <style>
@import 'vue-multiselect/dist/vue-multiselect.css';
</style>

page refreshes but it shouldn’t

when i submit form that displays fetched data (display,download form) page does not refresh but if i submit form that adds new user or update his data page refreshes. display, download form changes the html (displays data), script is linked with defer attribute
every form shouldn’t refresh. how to fix it?

forms:

<div class="content active">
            <form data-form-type="add">
              <input type="text" name="name" placeholder="Imie" />
              <input type="email" name="email" placeholder="E-mail" />
              <input
                type="text"
                name="status"
                placeholder="Status subskrypcji"
              />
              <button type="submit">Dodaj</button>
            </form>
          </div>
          <div class="content">
            <form data-form-type="display">
              <button type="submit">Wyświetl</button>
              <ul id="users"></ul>
            </form>
          </div>
          <div class="content">
            <form data-form-type="update">
              <input type="text" name="id" placeholder="ID klienta" />
              <input type="text" name="name" placeholder="Imię" />
              <input type="email" name="email" placeholder="E-mail" />
              <input
                type="text"
                name="status"
                placeholder="Status subskrypcji"
              />
              <button type="submit">Aktualizuj</button>
            </form>
          </div>
          <div class="content">
            <form data-form-type="delete">
              <input type="text" name="id" placeholder="ID klienta" />
              <button type="submit">Usuń</button>
            </form>
          </div>
          <div class="content">
            <form data-form-type="download">
              <button type="submit">Pobierz</button>
              <ul id="emails"></ul>
            </form>
          </div>

js:

const forms = document.querySelectorAll("form");

forms.forEach((form) => {
  form.addEventListener("submit", async (e) => {
    e.preventDefault();
    console.log("formualrz");
    debugger;
    const formType = form.dataset.formType || null;

    const formData = new FormData(form);

    formData.append("formType", formType);

    const response = await fetch(`http://localhost:3000/${formType}`, {
      method: "POST",
      body: formData,
    });

    try {
      console.log("formualrz");
      if (response.ok) {
        const responseData = await response.json();
        console.log(responseData);

        if (formType === "download") {
          const emailsBox = document.getElementById("emails");

          emailsBox.innerHTML = "";

          responseData.emails.forEach((email) => {
            const emailElement = document.createElement("li");
            emailElement.textContent = email;
            emailsBox.appendChild(emailElement);
          });
        } else if (formType === "display") {
          const usersBox = document.getElementById("users");

          usersBox.innerHTML = "";

          responseData.users.forEach((user) => {
            const userElement = document.createElement("li");
            let paragraph = document.createElement("p");

            paragraph.textContent = "ID: " + user.id;
            userElement.appendChild(paragraph);

            paragraph = document.createElement("p");

            paragraph.textContent = "Name: " + user.name;
            userElement.appendChild(paragraph);

            paragraph = document.createElement("p");

            paragraph.textContent = "Email: " + user.email;
            userElement.appendChild(paragraph);

            paragraph = document.createElement("p");

            paragraph.textContent = "Status: " + user.status;
            userElement.appendChild(paragraph);

            usersBox.appendChild(userElement);
          });
        } else if (formType === "update") {
          console.log("zakutalizowano");
        } else if (formType === "add") {
          console.log("dodano");
        }
      } else {
        console.error("Nie udało się wysłać danych");
      }
    } catch (error) {
      console.error("Błąd:", error);
    }
  });

  const submitButtons = form.querySelectorAll("button[type='submit']");
  submitButtons.forEach((button) => {
    button.addEventListener("click", async () => {
      const formType = form.dataset.formType || null;

      const formData = new FormData(form);

      formData.append("formType", formType);

      const response = await fetch(`http://localhost:3000/${formType}`, {
        method: "POST",
        body: formData,
      });

      try {
        console.log("formularz");
        if (response.ok) {
          const responseData = await response.json();
          console.log(responseData);

          if (formType === "download") {
            const emailsBox = document.getElementById("emails");

            emailsBox.innerHTML = "";

            responseData.emails.forEach((email) => {
              const emailElement = document.createElement("li");
              emailElement.textContent = email;
              emailsBox.appendChild(emailElement);
            });
          } else if (formType === "display") {
            const usersBox = document.getElementById("users");

            usersBox.innerHTML = "";

            responseData.users.forEach((user) => {
              const userElement = document.createElement("li");
              let paragraph = document.createElement("p");

              paragraph.textContent = "ID: " + user.id;
              userElement.appendChild(paragraph);

              paragraph = document.createElement("p");

              paragraph.textContent = "Name: " + user.name;
              userElement.appendChild(paragraph);

              paragraph = document.createElement("p");

              paragraph.textContent = "Email: " + user.email;
              userElement.appendChild(paragraph);

              paragraph = document.createElement("p");

              paragraph.textContent = "Status: " + user.status;
              userElement.appendChild(paragraph);

              usersBox.appendChild(userElement);
            });
          } else if (formType === "update") {
            console.log("zakutalizowano");
          } else if (formType === "add") {
            console.log("dodano");
          }
        } else {
          console.error("Nie udało się wysłać danych");
        }
      } catch (error) {
        console.error("Błąd:", error);
      }
    });
  });
});

`

i tried to use preventDefault but i doesn’t work

How to select this element in Javascript? – Chrome Extension

I’m new to javascript and I’ve been trying for an hour to select this from a web app:

<button type="button" class="zp-button zp_zUY3r zp_B5hnZ zp_rhXT_ zp_FVbJk finder-select-multiple-entities-button" fdprocessedid="jowqnd"><div class="zp_kxUTD" data-elem="button-label"><div class="zp_fwjCX" data-input="checkbox" data-cy-status="unchecked"></div></div><i class="zp-icon apollo-icon apollo-icon-caret-down-small zp_dZ0gM zp_j49HX zp_sGyhf"></i></button>

I’ve been trying to select it by the “zp_FVbJk” class.

const dropdownSelector = 'zp_FVbJk'
// Handles button and has to be the same in popup.js and content.js until I find a better solution
function sharedTempHandleButton() {
    console.log("sharedTempHandleButton() started.");

    let buttonToClick;

    buttonToClick = document.getElementsByClassName(dropdownSelector)[0];

    console.log(buttonToClick)

    if (buttonToClick) {
        console.log("Button found: ", buttonToClick);
        buttonToClick.click();
    } else {
        console.error('Button not found using the provided CSS selector');
    }
}

I’ve tried:

  • Changing selector to ‘.zp_FVbJk’
  • Using queryselector()

Correctly use useNavigate() with react-router v6 and createBrowserRouter (useNavigate() may be used only in the context of a componen)

I’m defining my router using createBrowserRouter and I have an Auth context provider that wraps . The issue I’m running into is the error:

Uncaught Error: useNavigate() may be used only in the context of a component.

useNavigate is being defined in my Auth Provider. Here is all of the necessary code. Does anyone know how to solve this.

Any help would be appreciated.

//context.jsx

const AuthContext = createContext({});

export const AuthProvider = ({ children }) => {
  const [auth, setAuth] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();

  const token = localStorage.getItem("token");

  useEffect(() => {
    if (!token) return;

    navigate(location.pathname);
  }, [setAuth]);

  const login = (token) => {
    localStorage.setItem("token", token);
    setAuth(false);
    navigate("/dashboard");
  };

  return (
    <AuthContext.Provider value={{ auth, setAuth, login }}>
      {children}
    </AuthContext.Provider>
  );
};

export default AuthProvider;


//router.jsx: 

const AuthLayout = () => (
  <AuthProvider>
    <Outlet />
  </AuthProvider>
);

const router = createBrowserRouter([
  {
    element: <AuthLayout />,
    children: [
      {
        path: "/",
        element: <LoginScreen />,
        errorElement: <ErrorPage />,
      },
      {
        path: "/dashboard",
        element: <Dashboard />,
        errorElement: <ErrorPage />,
      },
    ],
  },
]);

export default router;


//app.jsx

function App() {
  return (
    <>
      <RouterProvider router={router} fallbackElement={<p>Loading...</p>} />
    </>
  );
}

export default App;

//main.jsx

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <AuthProvider>
      <App />
    </AuthProvider>
  </React.StrictMode>
);


I can’t simply wrap everything in BrowserRouter because that would be using router twice. I was able to get it to work using the old route/router way but would like to utilize createBrowserRouter. I have looked at many other solutions but no one was doing quite what I was doing and it wasn’t very helpful for my use case.

How to load dotenv config and initializeApp only once in firebase function second generation

I have to load dotenv config and admin.initializeApp methods in every function file. Precisely, I have to write below code in every file:

import { config } from "dotenv";
import * as admin from "firebase-admin";
config();

if (!admin.apps.length) admin.initializeApp();

Is there a way to write this code only in index file and all functions get access to env variables as well as app get initialized in all functions.