How to pass a axios response to a function

I try this code and get an infinite loop

request.jsx

import { useEffect, useState } from 'react';
import axios from 'axios';

export async function getCategories() {
    const [categories,setCategories]= useState();
    try {
       await useEffect(() => {
            axios.get("http://localhost:3001/api/req/categories",).then(function (res) {
                const response = JSON.stringify(res.data)
                setCategories(response);
            });
    
            
   
    
        }, [])
            return categorias;
    } catch (error) {
        console.log(error);
    }

}

item_new.jsx


import { getCategories } from ".request";
import { useEffect, useState } from "react";
const [categorieSelect, setCategorieSelect] = useState();

getCategories().then(response => {
    
    try {
      const res = JSON.parse(response);
     
      setCategorieSelect(res)

    } catch (error) {
      console.log(error)
    }
 console.log(categorieSelect)  // infinite loop
  })

I also try to put a useEffect and get this error

react-dom.development.js:15408 Uncaught (in promise) 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.<

import { getCategories } from ".request";
import { useEffect, useState } from "react";
const [categorieSelect, setCategorieSelect] = useState();

getCategories().then(response => {
    
    try {
      useEffect(()=>{   
      
       const res = JSON.parse(response);
       setCategorieSelect(res)

   },[])
   

    } catch (error) {
      console.log(error)
    }
 console.log(categorieSelect)  // infinite loop
  })

Why does npm install spawn exponentially greater numbers of processes?

I have a number of JavaScript packages hosted in private GitHub repositories. I’ve found that the more of those packages I include as dependencies the more processes npm install spins up. This is getting to the point where a single run of npm install eats all 16 CPU cores, spawns hundreds of npm install processes, and takes hours to complete, if it does not fail altogether.

This image shows some of the packages I have authored and am using and the way in which they depend on one another:

Dependency Tree

  • Running an install at the Node level takes about 6 seconds and spawns no additional processes.
  • Running an install at the Lambda level takes about 13 seconds and spawns 3 additional processes.
  • Running an install at the Entity level takes about 3 minutes and spawns 22 additional processes.
  • Running an install at the Core level takes about 26 minutes and spawns at least 150 additional processes (some complete before others spawn, so it is difficult to get an exact count).
  • Running an install in a project that includes the Core package takes about 2 hours and spawns hundreds of additional processes.

I am running Node 20.18.0 with NVM 0.39.1.

My private dependencies are specified in the package.json dependencies section in the format:

"package-name": "github:username/repo.name#semver:X.X.X"

I have no problems with authentication and retrieving the packages is very fast. The issue seems to occur after the packages have been downloaded.

The Util and Test packages are ES modules, the rest are CommonJS2.

I’ve deleted the package-lock.json files and node_modules directories and tried running a fresh install.

I’ve tried installing the private dependencies one by one.

I have tried some hacky methods to try to determine the underlying cause, such as bundling the lower level dependencies using webpack and changing the private dependencies to dev-dependencies.

I’ve also tried using yarn, but it has the same problem.

Project is not receiving data from API

My project is supposed to display products from an API that I hosted on Github Pages. I used vanilla javascript to create the code. Here it is:

import { allProductsUrl } from "./utils.js";

const fetchProducts = async () => {
  const response = await fetch(allProductsUrl).catch((err) => console.log(err));
  if (response) {
    return response.json();
  }
  return response;
};

export default fetchProducts;

When I inspected the browser, I wanted an error message to show up in the console. Unfortunately, there is no error message when going into inspect mode. Even if I change the console log to a simple string message I’m still not getting any results within the console. Here is the code where I choose to invoke the function that I created:

import "./src/toggleSidebar.js";
import "./src/cart/toggleCart.js";
import "./src/cart/setupCart.js";
// specific imports
import fetchProducts from "./src/fetchProducts.js";
import { setupStore, store } from "./src/store.js";
import display from "./src/displayProducts.js";
import { getElement } from "./src/utils.js";

const init = async () => {
  const products = await fetchProducts();
  if (products) {
    // add products to the store
    setupStore(products);
    const featured = store.filter((product) => product.featured === true);
    display(featured, getElement(".featured-center"));
  }
};

window.addEventListener("DOMContentLoaded", init);

I’ve tested my API on Postman and I received a response. Please let me know how I can get a response within my project.

How to set AppKit (Web3Modal) provider for web3.js?

Dear smart contract front-end developers,

As you know, AppKit is the new verion of Web3Modal. I am using it in a web javascript program to show a dialog to connect the web page to the desired wallet. Then I want to use Web3.js to interact with some smart contracts.

So I use this program:

import { createAppKit, ReownAppKitModal } from '@reown/appkit'
import { bsc } from '@reown/appkit/networks'
import { WagmiAdapter } from '@reown/appkit-adapter-wagmi'
import { reconnect } from '@wagmi/core'
import { Web3 } from 'web3'
import { useAppKitProvider, useAppKitAccount } from "@reown/appkit/react";

const projectId = '...'
const networkList = [ bsc]
const wagmiAdapter = new WagmiAdapter({
    projectId,
    networks: networkList
})
const metadata = {
    name: '...',
    description: '...',
    url: 'https://...',
    icons: ['...'],
};
const modal = createAppKit({
    adapters: [wagmiAdapter],
    networks: networkList,
    projectId,
    metadata: metadata,
    themeMode: 'light'
})
reconnect(wagmiAdapter.wagmiConfig)
const { walletProvider } = useAppKitProvider();
console.log(walletProvider);
const web3 = new Web3(xxx);

Now I want to use a Web3 provider instead of xxx in the last line of the above program.

For example if I use window.ethereum it works only if I use Metamask wallet.

What can I use instead of Web3 provider so it connects to the wallet that selected in AppKit modal dialog?

I will appreciate you, even if you give a solution in Web3Modal.

heading and list don’t work No change is made by clicking in ckEditor5 , next js14

I have a problem using ckEditor in nextjs14…
I have done according to the document and I have done the settings according to the code I have written
see output image

i have use @ckeditor/ckeditor5-react & ckeditor5

I expect it to be numbered when I click on a numbered list, or enlarged when I select a word and click on Heading.

 <CKEditor
            editor={ ClassicEditor }
            config={ {
                toolbar: {
                    items: [
                        'undo',
                        'redo',
                        '|',
                        'heading',
                        '|',
                        'fontSize',
                        'fontFamily',
                        '|',
                        'bold',
                        'italic',
                        'underline',
                        'strikethrough',
                        'removeFormat',
                        '|',
                        'link',
                        'insertImage',
                        'ckbox',
                        'mediaEmbed',
                        'insertTable',
                        'highlight',
                        'blockQuote',
                        '|',
                        'alignment',
                        '|',
                        'bulletedList',
                        'numberedList',
                        'multiLevelList',
                        '|',
                        'accessibilityHelp'
                    ]
                },
                plugins: [
                    Alignment,
                    Autoformat,
                    AutoLink,
                    Autosave,
                    BlockQuote,
                    Bold,
                    FontSize,
                    FontFamily,
                    Heading,
                    Highlight,
                    Image,
                    ImageCaption,
                    ImageResize,
                    ImageStyle,
                    ImageToolbar,
                    ImageUpload,
                    Italic,
                    Link,
                    List,
                    MediaEmbed,
                    Mention,
                    Paragraph,
                    PasteFromOffice,
                    PictureEditing,
                    RemoveFormat,
                    Strikethrough,
                    Table,
                    TableCaption,
                    TableCellProperties,
                    TableColumnResize,
                    TableProperties,
                    TableToolbar,
                    Underline,
                    Undo,
                ],
                heading: {
                    options: [
                        {
                            model: 'paragraph',
                            title: 'Paragraph',
                            class: 'ck-heading_paragraph'
                        },
                        {
                            model: 'heading1',
                            view: 'h1',
                            title: 'Heading 1',
                            class: 'ck-heading_heading1'
                        },
                        {
                            model: 'heading2',
                            view: 'h2',
                            title: 'Heading 2',
                            class: 'ck-heading_heading2'
                        },
                        {
                            model: 'heading3',
                            view: 'h3',
                            title: 'Heading 3',
                            class: 'ck-heading_heading3'
                        }
                    ]
                },
                image: {
                    toolbar: [ 'imageTextAlternative', '|', 'ckboxImageEdit' ]
                },
                initialData: '<p>Hello from CKEditor 5 in React!</p>'
            } }
        />

How to display name values for numerical enum in Vue? [duplicate]

I am building a little vue.js webapp tool to view and edit a backend config file (formatted as a json). The object has an enum field which is represented on the backend as a uint, but I would like to somehow map the display name to the numerical value in the json and then display the options in a dropdown select. I currently have a v-for element that loops over each config record and displays each field.

The object looks like:

{records:[
  {
    id:"12345",
    target:678,
    src:"path/to/src"
    operator:0 // backend enum where values 0,1,2... map to the below operators
  },
  ... // more records
}

I currently have the following for the dropdown:

<label class="recorditem">Comparison Operator:
  <select v-model="record.operator">
    <option>EQ</option>   // should map to 0
    <option>NEQ</option>  // should map to 1
    <option>GT</option>   // should map to 2
    <option>GTE</option>  // should map to 3
    <option>LT</option>   // should map to 4
    <option>LTE</option>  // should map to 5
  </select>
</label>

Is there any way to take the numerical value in the json and with javascirpt/vue display the text “EQ”, “NEQ”, etc. in the dropdown on the webpage and then when the user clicks on the selected option in the dropdown, have it update the data with the numerical value (instead of the text) as defined by the backend?

EDIT: I deleted a section of code that displayed how the backend was generating the json and why it’s an enum but that somehow got the question marked as a duplicate so it is now removed.

Why does my JavaScript promise chain return undefined despite having a return statement? [closed]

 function fetchData() {
return fetch('https://api.example.com/data') // Replace with a real API endpoint
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json(); // Parse the JSON data
    })
    .then(processedData => {
        console.log("Processed Data:", processedData);
        return processedData; // Return the processed data
    })
    .catch(error => {
        console.error("An error occurred:", error);
        throw error; // Propagate the error
    });

}
Function Documentation:
Added a function-level comment to explain its purpose and return type. This makes it easier for other developers to understand the function.

Error Handling:

Used if (!response.ok) to explicitly check for HTTP response status errors (e.g., 404, 500).
Added a descriptive error message using throw new Error().
Data Transformation:
In the second .then() block, data is processed further, such as extracting important fields and adding a timestamp. This is a common use case for APIs that return large JSON objects.

Comments for Clarity:
Inline comments explain what each part of the code does. This helps make the code easier to follow for beginners.

Reusable Design:
By returning a Promise, this function can be reused in other parts of your application for API requests.

Error Propagation:
Errors are logged and re-thrown so the calling code can handle them. This ensures robust error handling at every level.

MVC framework for javascript instead of asp.net

I have to do MVC structure website for school project and I have some experience with react and next.js. We are doing it in asp.net but I am not good with C# so I want to use javascript. I tried sails js but I am having tough time with it but unfortunately it didn’t connect foreign keys in database that I need and my teacher didn’t like that. The only requirment for the project is that it has to be done in MVC structure so I want to know. Is there any way to make Next.js into MVC like structure so it will be good for the project? If not is there any good js framework with MVC structure that I can learn fast? (I have about 3-4weeks and database is already done in sql) There has to be migration to database with models. There has to be some roles so for example admin can see page in views where are all users and can edit their rights but user can’t see that page.

I tried to use sails.js but it doesn’t work as I wanted

How to reproduce horizontal flow layout as custom layout in embed.diagrams.net / draw.io?

I would like to programmatically trigger a layout operation for diagrams.net.

I would like to use the horizontal flow layout that is available in the ui and as style:

style="childLayout=flowLayout;flowOrientation=west;"

However, for the api there is no type mxFHorizontalFlowLayout.

=> How to reproduce the horizontal flow layout specified as style, based on the supported layout types?

=> Or how can I trigger an update of the layout, based on the already specified style? (Unfortunately, draw.io does not apply the style automatically but only after manual edits.)

I tried to use mxHierarchicalLayout but I get different results.

        /* available layouts:
        https://www.drawio.com/doc/faq/apply-layouts#custom-layouts

        0 : "mxHierarchicalLayout"
        1 : "mxCircleLayout"
        2 : "mxCompactTreeLayout"
        3 : "mxEdgeLabelLayout"
        4 : "mxFastOrganicLayout"
        5 : "mxParallelEdgeLayout"
        6 : "mxPartitionLayout"
        7 : "mxRadialTreeLayout"
        8 : "mxStackLayout
        */

   function sendLayoutMessage() {{
        // tries to apply a horizontal flow layout
        console.log('layout');
        var iframe = document.getElementById('drawio-iframe');
        var layoutMessage = JSON.stringify({{
            action: 'layout',
            layouts: [
                {{
                    "layout": "mxHierarchicalLayout",
                    "config": {{
                      "orientation": "west",
                      "intraCellSpacing": 0.1,
                      "interRankCellSpacing": 0.1,
                      "interHierarchySpacing": 0.1,
                      "parallelEdgeSpacing": 0.1
                    }}                       
                }}
            ]
        }});
        iframe.contentWindow.postMessage(layoutMessage, '*');
    }}

How to redirect from the login portal using Flask

I have been developing a pretty basic site, I have used tons of GPT but one issue both me and GPT have been unable to figure out is how after login, the site is not able to redirect.
I am trying to redirect it to another page after a successful login. A JWT token is being generated but something I have not been able to figure out.

from flask import Flask, request, jsonify, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
from flask_cors import CORS
from flask_jwt_extended import verify_jwt_in_request, get_jwt_identity
import os

# Flask app configuration
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:Arjun2003%23%[email protected]/stockroom_db'
app.config['JWT_SECRET_KEY'] = 'your_jwt_secret_key'  # Replace with a strong secret key
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # Disable to save resources

# Initialize extensions
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
jwt = JWTManager(app)

# User model definition
class User(db.Model):
    __tablename__ = 'users'
    user_id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    email = db.Column(db.String(100), unique=True, nullable=False)
    password_hash = db.Column(db.String(255), nullable=False)
    created_at = db.Column(db.DateTime, default=db.func.current_timestamp())

    def set_password(self, password):
        self.password_hash = bcrypt.generate_password_hash(password).decode('utf-8')

    def check_password(self, password):
        return bcrypt.check_password_hash(self.password_hash, password)

# Signup route for user registration
@app.route('/signup', methods=['POST'])
def signup():
    data = request.json
    username = data.get('username')
    email = data.get('email')
    password = data.get('password')

    # Check if username or email already exists
    if User.query.filter((User.username == username) | (User.email == email)).first():
        return jsonify({"error": "Username or Email already exists"}), 400

    # Create a new user instance
    new_user = User(username=username, email=email)
    new_user.set_password(password)
    
    # Save the new user to the database
    db.session.add(new_user)
    db.session.commit()

    return jsonify({"message": "User registered successfully"}), 201

# Login route for user authentication
@app.route('/login', methods=['POST'])
def login():
    data = request.json
    username = data.get('username')
    password = data.get('password')

    # Find the user by username
    user = User.query.filter_by(username=username).first()
    
    # Check if user exists and password is correct
    if user and user.check_password(password):
        # Create JWT token
        access_token = create_access_token(identity=user.user_id)
        return jsonify({"access_token": access_token}), 200

    return jsonify({"error": "Invalid username or password"}), 401

@app.before_request
def handle_options_request():
    if request.method == "OPTIONS":
        return jsonify({"status": "OK"}), 200


@app.route('/myStockroom', methods=['GET'])
@jwt_required()  # Enforce JWT validation
def my_stockroom():
    try:
        # Log the Authorization header
        auth_header = request.headers.get('Authorization')
        print(f"Authorization Header Received: {auth_header}")

        # Extract user ID from JWT
        user_id = get_jwt_identity()
        print(f"User ID from JWT: {user_id}")

        # Fetch user from the database
        user = User.query.get(user_id)
        if user:
            return jsonify({"username": user.username}), 200
        else:
            return jsonify({"error": "User not found"}), 404
    except Exception as e:
        print(f"Error in myStockroom route: {e}")
        return jsonify({"error": "Unauthorized access"}), 401

CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True, expose_headers=["Authorization"])

# Main entry point for running the application
if __name__ == "__main__":
    # Create tables if they don't exist
    with app.app_context():
        db.create_all()
    app.run(host="127.0.0.1", port=5555, debug=True)

The above code is my app.py

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stockroom - Manage Your Inventory Seamlessly</title>
<link rel="stylesheet" href="StockRoomstaticstyle.css">
</head>
<body>

<div class="container">
    <div class="logo">
        <img src="" alt="Stockroom Logo">
    </div>
    <div class="tagline">Manage your inventory, seamlessly.</div>
    <div class="button-container">
      <button class="cta-button" onclick="openModal('signup')">SIGN UP</button>
      <button class="cta-button" onclick="openModal('login')">LOGIN</button>
  </div>
</div>

<img src="StockRoomstaticStockRoom Frontend Design_20240914_161105_0000.png" alt="Background Image" class="background-image">

<!-- Signup Modal -->
<div id="signupModal" class="modal">
  <div class="modal-content">
    <span class="close-button" onclick="closeModal('signup')">&times;</span>
    <h2>Sign Up</h2>
    <label class="form-label">Username</label>
    <input type="text" class="form-input" id="signupUsername">
    <label class="form-label">Email</label>
    <input type="email" class="form-input" id="signupEmail">
    <label class="form-label">Password</label>
    <input type="password" class="form-input" id="signupPassword">
    <button class="form-button" onclick="handleSignup()">Sign Up</button>
    <p class="message" id="signupMessage"></p>
  </div>
</div>

<!-- Login Modal -->
<div id="loginModal" class="modal">
  <div class="modal-content">
    <span class="close-button" onclick="closeModal('login')">&times;</span>
    <h2>Login</h2>
    <label class="form-label">Username</label>
    <input type="text" class="form-input" id="loginUsername">
    <label class="form-label">Password</label>
    <input type="password" class="form-input" id="loginPassword">
    <button class="form-button" onclick="handleLogin()">Login</button>
    <p class="message" id="loginMessage"></p>
  </div>
</div>

<script>
    // Open modal function
function openModal(type) {
    document.getElementById(type + 'Modal').style.display = 'block';
}

// Close modal function
function closeModal(type) {
    document.getElementById(type + 'Modal').style.display = 'none';
}

// Handle signup function
async function handleSignup() {
    const username = document.getElementById('signupUsername').value;
    const email = document.getElementById('signupEmail').value;
    const password = document.getElementById('signupPassword').value;
    const signupMessage = document.getElementById('signupMessage');

    try {
        const response = await fetch('http://127.0.0.1:5555/signup', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ username, email, password })
        });

        const data = await response.json();

        if (response.ok) {
            signupMessage.style.color = "green";
            signupMessage.innerText = "Signup successful! Please log in.";
            closeModal('signup');
        } else {
            signupMessage.style.color = "red";
            signupMessage.innerText = data.error || "Signup failed. Try again.";
            console.error("Signup Error:", data); // Log detailed error info
        }
    } catch (error) {
        signupMessage.innerText = "An error occurred. Please try again.";
        console.error("Network Error:", error); // Log network error details
    }
}

// Handle login function
async function handleLogin() {
    const username = document.getElementById('loginUsername').value;
    const password = document.getElementById('loginPassword').value;
    const loginMessage = document.getElementById('loginMessage');

    try {
        const response = await fetch('http://127.0.0.1:5555/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ username, password })
        });

        const data = await response.json();

        if (response.ok && data.access_token) {
            // Store the JWT token in sessionStorage
            sessionStorage.setItem('token', data.access_token);
            console.log('Stored Token:', sessionStorage.getItem('token'));

            // Update the message to indicate success
            loginMessage.style.color = "green";
            loginMessage.innerText = "Login successful! Redirecting...";

            // Close the modal
            closeModal('login');

            // Redirect to myStockroom page after a brief delay
            setTimeout(() => {
                window.location.href = "http://127.0.0.1:5555/myStockroom"; // Use absolute URL
            }, 1500);
        } else {
            // Handle login failure
            loginMessage.style.color = "red";
            loginMessage.innerText = data.error || "Login failed. Check credentials.";
        }
    } catch (error) {
        // Handle network errors
        loginMessage.style.color = "red";
        loginMessage.innerText = "An error occurred. Please try again.";
        console.error("Network Error:", error); // Log the error for debugging
    }
}

// Fetch user data for myStockroom page
window.onload = function () {

  const token = sessionStorage.getItem('token'); // Retrieve JWT token

    if (!token) {
      alert("You are not logged in!");
      window.location.href = "/login"; // Redirect if no token
      return;
    }

    fetch('/myStockroom', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${sessionStorage.getItem('token')}`// Add token to Authorization header
        }
    })
    .then(response => {
            if (response.status === 401) {
                // Handle unauthorized access
                alert("Session expired. Please log in again.");
                sessionStorage.removeItem('token'); // Clear invalid token
                window.location.href = "/login";
            } else {
                return response.json();
            }
        })
        .then(data => {
            if (data.username) {
                document.getElementById('username').textContent = data.username; // Update username
            } else {
                console.error("Error: Username not found.");
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert("An error occurred while fetching user data.");
        });
};

// Close modals if clicked outside
window.onclick = function (event) {
    const signupModal = document.getElementById('signupModal');
    const loginModal = document.getElementById('loginModal');
    if (event.target === signupModal) signupModal.style.display = 'none';
    if (event.target === loginModal) loginModal.style.display = 'none';
};

  </script>

</body>
</html>

the above code is my login page

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Stockroom Inventory</title>
<link rel="stylesheet" href="StockRoomstaticstyle.css">
</head>
<body>

    <div class="sidebar">
        <img src="StockRoomstaticstockroom White.png" alt="Stockroom Logo">
        <p class="highlight">my stockroom</p>
        <p>inventory</p>
        <p>new order</p>
        <div class="bottom-links">
            <p>account</p>
            <p>homepage</p>
            <p>help</p>
        </div>
    </div>
    
    <div class="banner">
        <h1>My Stockroom</h1>
    </div>
    
    <div class="main-content">
        <h1>Welcome, <span id="username"></span>!</h1>
        <div class="form-container">
            <div>
                <label class="input-label">DATE:</label>
                <input type="text"/>
            </div>
            <div>
                <label class="input-label">ORDER#:</label>
                <input type="text"/>
            </div>
            <div>
                <label class="input-label">CUSTOMERNAME:</label>
                <input type="text"/>
            </div>
            <div>
                <label class="input-label">TOTAL ORDER VALUE (TOV):</label>
                <input type="text"/>
            </div>
        </div>
    </div>
    
    <!-- Add this JavaScript at the end of the body section -->
    <script>
        // Fetch user data using JWT token
        window.onload = function() {
            const token = sessionStorage.getItem('token'); // Retrieve the JWT token from sessionStorage
    
            // Check if the token exists
            if (!token) {
                alert("You are not logged in!");
                window.location.href = "/login"; // Redirect to login page if not logged in
                return;
            }
    
            // Make a fetch request to the /myStockroom endpoint to get user data
            fetch('/myStockroom', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`  // Add Authorization header
                }
            })
            .then(response => response.json())
            .then(data => {
                // Use data to update the UI (for example, show username or other info)
                if (data.username) {
                    document.getElementById('username').textContent = data.username; // Update username dynamically
                } else {
                    console.error("Error: Username not found in response.");
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert("An error occurred while fetching user data.");
            });
        };
    </script>
    
    </body>
    </html>

This code is the page it should redirect to, please help me figure this redirection

How to click an aria button with Puppeteer?

I want to click the Facebook’s Photo/video button when creating a post. The element is:

<div aria-label="Photo/video" aria-pressed="false" class="..." role="button" tabindex="0">
  <div><div><div class="..."><div class="..."><div class="...">
    <img class="..." alt="" src="https://static.xx.fbcdn.net/rsrc.php/v3/y7/r/Ivw7nhRtXyo.png?_nc_eui2=AeHY6dd2udiKCsGGc3_l3Lj2PL4YoeGsw5I8vhih4azDks5jrq6FoGG-iYDYkCJ4e3z08U_itrGNYjc5wzxwesxH" style="height: 24px; width: 24px;">
  </div><div class="..." role="none" data-visualcompletion="ignore" style="inset: 0px;"></div></div></div></div><div><div></div></div></div></div>

According to Page interactions | Puppeteer, I think the correct code is:

await page.locator('::-p-aria([name="Photo/video"][role="button"])').click();

But it doesn’t click. Changing name to label doesn’t help. Do you know how to make it work?

Change values of input dynamically added on change select option

I am using add remove input fields set via jquery.

I want to set input value of input depend on select option selected in that field set.

How to achieve this ?

Code:

var html_row = '<tr><td class="firstcell"></td><td><select name="is_member[]" ><option value="">Select</option><option value="Yes">Yes</option><option value="No">No</option></select></td><td><input name="membership_number[]" value=""></td><td><input type="button" name="remove" id="remove_row" class="btn btn-info"  value="Remove This Section" tabindex="-1"></td></tr>';

var max = 50;
var x = 1;

$('#add_row').click(function() {
  if (x <= max) {
    $('#table_fields').append(html_row);
    var els = $(".firstcell");
    for (var i = 1; i < els.length; i++) {
      els[i].innerHTML = i + 1;
      $("select[name='is_member[]']").on('change', function() {

        var member_status = $(this).val();
        if (member_status == "No") {
          $("input[name='membership_number[]']").val("Not Member");
        } else {
          $("input[name='membership_number[]']").val("");
        }
      });
    }
  }
});


$('#table_fields').on('click', '#remove_row', function() {
  $(this).closest('tr').remove();
  x--;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<table id="table_fields">
  <tr>
    <td></td>
    <td>Is Member</td>
    <td>Membership Number</td>
  </tr>

  <tr>
    <td class="firstcell">1</td>
    <td>
      <select name="is_member[]">
        <option value="">Select</option>
        <option value="Yes">Yes</option>
        <option value="No">No</option>
      </select>
    </td>
    <td><input name="membership_number[]" value=""></td>
    <td></td>
  </tr>
</table>
<br><br>
<div class="text-center"><input type="button" name="add" id="add_row" class="btn btn-primary" value="Add Input Row" tabindex="-2"> </div>

With this code, value of membership_number field get changed but it is getting changed for all added rows of field set’s input fields.

I want to change it only for select option of that specific field set in a added row.

JSFIDDLE

In jsfiddle, you can check by adding rows and changing is member option to No… all input fields values in membership number gets changed…

Is there a way to invoke window.onload using Interop inside Blazor Wasm Component

I am trying to create an application which uses Moneris Hosted Payment Solution- basically implementing an iframe which needs to register an event on window on load. It has postmessage api, which when invoked will return a message, and what I can do is register a callback function so I can decode/use those messages.

The problem is I am not sure how can I invoke this window.onload on blazorwasm. I have tried to implement this but at the moment it is not working.

I am sharing my code. Your help would be a lot appreciated.

this is in my Blazor Page.

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    Console.WriteLine("hello test");
    if (firstRender)
    {
        Console.WriteLine("invoking this function");
        await JSRuntime.InvokeVoidAsync("MonerisEvents.setWindowOnLoad");
    }
}

This is my javascript code in wwwroot.

window.MonerisEvents = 
{
    doMonerisSubmit: function doMonerisSubmit() {
        var monFrameRef = document.getElementById('monerisFrame').contentWindow;
        monFrameRef.postMessage('tokenize', 'https://esqa.moneris.com/HPPtoken/index.php');
        //change link according to table above
        return false;
    },

    respMsg : function (e) {
        var respData = eval("(" + e.data + ")");
        console.log(respData);
        console.log(respData.responseCode);
        console.log(respData.errorMessage);
        console.log(respData.bin);
        console.log(respData.dataKey);


        document.getElementById("monerisResponse").innerHTML = e.origin + " SENT " + " - " +
            respData.responseCode + "-" + respData.dataKey + "-" + respData.errorMessage;
        document.getElementById("monerisFrame").style.display = 'none';
    },

    setWindowOnLoad : function setWindowOnLoad()
    {
        var self = this;
        window.onload = function () {
            console.log("was here second");
            if (window.addEventListener) {
                window.addEventListener("message", self.respMsg, false);
            }
            else {
                if (window.attachEvent) {
                    window.attachEvent("onmessage", self.respMsg);
                }
            }
        }
    } 
}

Shallow copying initialState to pinia state is actually doing a deep copy

I use a predefined initialState and I am using shallow copy to assign it to the state.

import { defineStore } from 'pinia';
const storeName = 'exampleStore';
const initialAppState = {
  booleanValue: false,
  id: '',
  object1: {},
  object2: {},
  array2: [],
}
const useExampleStore = defineStore(storeName, {
  state: () => ({ ...initialAppState }),
  getters: {},
  actions:{},
});
export default useExampleStore;

In the above case, since I am using a shallow copy to assign the initialAppState to the state of the pinia store, updating the state’s primitive values won’t affect the initialAppState. But updating the objects or arrays should also change the values in initialAppState because we are using ShallowCopy.

The above mentioned should be the case, instead when I change the objects or arrays it is not affected in the initialAppState.

Even though this is the ideal case, I am curios on how it works. I am sure it has to do something with the pinia setting the state. Could someone please explain how this works.

Thanks