Linking to another html page is not working?

I tried to link the settings tab as shown in the sidebar to a new HTML page called (settings.html), but when I click on the settings it does not direct me to the (settings.html) page.

settings tab on the sidebar

Both HTML pages use the same external JavaScript file, and I only was able to navigate to the settings page from the sidebar, when I removed the JavaScript file from the HTML code.

This is the website code on GitHub
[https://github.com/Jehad-Sauafth/Dashboard.git]

ElectronJS, how verify if the user is logged in backend express session directly from the main process

I cant find where i fail to check session with my electron app. My application is composed from a client site (main.js, preload.js and renderer (with some html files of course)), and a backend side in node.js with Express. All work fine between the too, excepte in one case: The verify if one user have a session in the backend for auto-login when the user start the App.This is the main.js (client side) file:

axios.get('http://localhost:9090/oauth/express-session-exist')
.then(response => {
  if (response.data.success) {
    const userIsConnected = store.get('user_publickey');
    if (userIsConnected) {
      if (store.get('user_active') == 'false') {
     mainWindow.loadFile('discovery.html');
      } else {
    mainWindow.loadFile('app.html');
      }
    } else {
      mainWindow.loadFile('oauth.html');
    }
   } else {
     const userIsConnected = store.get('user_publickey');
     if (userIsConnected) {
       store.clear();
     }
     mainWindow.loadFile('oauth.html');
   }
})
.catch(error => {
  console.error(error);
  mainWindow.loadFile('oauth.html');
});

And this is the backend fonction:

router.get('/express-session-exist', (req, res) => {
  if (req.session.user) {
    res.json({ success: true, data: req.session.user });
  } else {
    res.json({ success: false });
  }
});

And i am pretty sure the session is well created when i login my user for the first time with this backend function:

  // Login
  router.post('/login', async (req, res) => {
    const { email, password } = req.body;
    try {
      const existingUser = await oauthModel.findUserByEmail(email);
      if (existingUser) {
        const passwordMatch = await bcrypt.compare(password, existingUser.user_password);
        if (passwordMatch) {

          // Here, i created the express-session and put in value, then return the value to
          // Electron. A console.log() in the client show prefectly the data of the session.

          req.session.user = {
            publickey: existingUser.user_publickey,
            regenerativekey: existingUser.user_regenerativekey,
            email: existingUser.user_email,
            alias: existingUser.user_alias,
          };


          const toElectron = req.session.user;
          res.status(200).json({ success: true, message: 'user-logged-in', user: toElectron });
        } else {
          res.status(401).json({ success: false, message: 'wrong-password' });
        }
      } else {
        res.status(401).json({ success: false, message: 'cant-find-email' });
      }
    } catch (error) {
      console.log(error)
      res.status(500).json({ success: false, message: 'ie500', error });
    }
  });

i dont know where to look at this point, AXIOS send request with the cookie so i dont know… Thank for reading me guys.

For informations this is my app.js:

  
  // app.js

  // Express setup
  const express = require('express');
  const session = require('express-session');
  const app = express();
  const port = 9090;

  // Chargement des modules
  const http = require('http');
  const server = http.createServer(app);
  const cors = require('cors');
  const bodyParser = require('body-parser');

  // Utiliser les sessions
  const sessionMiddleware = session({
    secret: 'mySecret',
    resave: true,
    saveUninitialized: true,
    cookie: {
      sameSite: 'Lax',
      maxAge: 1000 * 60 * 60 * 24 * 1000,
      secure: false // CARE PRODUCTION
    }
  });
  
  app.use(express.static('public'));
  app.use(cors({
    origin: ['http://localhost:9090'],
    credentials: true
  }));
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(sessionMiddleware);
  
  // Declaration Controllers
  const oauthController = require('./controllers/oauth');

  // Use Controllers
  app.use('/oauth', oauthController);

  server.listen(port, () => {
    console.log(`Server listening :${port}`);
  });

I expect my route /express-session-exist to see that a session is created and return true. But she constantly return false.

Developer menu shows errors in the app, but server launches successfully

I have some code for a React Application, and there’s no errors when the app is tested, but it shows a blank page in the server. Upon closer inspection, it shows things like “Invalid hook call” or “uncaught type error” within the browser developer window. These are the exact errors

react.development.js:209  Warning: 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

Here’s the App.js files and the Index.js files. I’m using tailwindcss that’s imported in the index.css file. I haven’t yet made the pages for the links present in the header.

App.js

import React from 'react';
import { Link } from 'react-router-dom';
const Header = () => {
  return (
    <div className="header flex justify-between items-center py-4 px-6">
      <div className="links flex justify-end w-2/3">
        <Link to="/" className="mx-4 text-purple-600 font-cursive"> Home </Link>
        <Link to="/services" className="mx-4 text-purple-600 font-cursive"> Services </Link>
        <Link to="/contact" className="mx-4 text-purple-600 font-cursive"> Contact </Link> </div>
      <div className="title"> <h1 className="text-3xl text-pink-600 font-cursive">The Salon</h1> </div> </div>);
};
export default Header;

Index.js –

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import Header from './App';
import reportWebVitals from './reportWebVitals';

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

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint.

What does an object destructuring pattern used as the rest property of an array destructuring pattern stand for?

The MDN Web Docs have this example:

Using a binding pattern as the rest property

The rest property of array destructuring assignment can be another array or object binding pattern. This allows you to simultaneously unpack the properties and indices of arrays.

const [a, b, ...{ pop, push }] = [1, 2];
console.log(a, b); // 1 2
console.log(pop, push); // [Function pop] [Function push]

What are those pop and push functions and how to use them?

> pop()
Uncaught TypeError: Cannot convert undefined or null to object
    at pop (<anonymous>)
> push(3)
Uncaught TypeError: Cannot convert undefined or null to object
    at push (<anonymous>)

Disable scrolling on visual viewport size changes (e.g. when zooming)

When zooming in, the visual viewport size changes, and the scrollbars appear. Is there a way to disable scrolling in that situation?

Note that I mean zooming by touchpad (pinch zooming), not by ctrl + mouse wheel.

gif demo

I just want to disable scrolling for the visual viewport, not other possible scrollable elements.
(I’ve already found a way to disable scrolling for all scrollable elements here: How to disable scrolling temporarily?)

And note that overflow:hidden obviously doesn’t relate to this problem

React component not updating when state data changes

I have a react component Project.js and Table.js. I am trying to make it so when a chooses files inside Project.js, it sends those files to Table.js to be displayed.

So inside Project.js, the default for the state tableData is set with 2 elements:

  const [tableData, setTableData] = useState([
    [
      "itemId",
      "<div style='cursor: pointer;'> = num</div>",
      "<input type='checkbox'>",
      "metaTitle A"
    ],
    [
      "itemId",
      "<div style='cursor: pointer;'> = num</div>",
      "<input type='checkbox'>",
      "metaTitle B"
    ],
  ]);

This gets passed into the Table.js component like so:

<Table tableData={tableData} />

And get displayed correctly, I even have some code that prints out a list of the tableData items from within Project.js

    <ul>
      <h3>tableData:</h3>
      {tableData.map((tableRow) => (
        <li key={tableRow[3]}>
          {tableRow[3]}
        </li>
      ))}
    </ul>

As you can see, the two rows get displayed inside Table.js and Project too just fine
enter image description here

Then when the user drags/selects files, this function gets called which sets the updates the state var with a third row ‘metaTitle C’

  const handleFilesSelect = (files) => {
    console.log('Setting selectedFiles = ', files)
    setSelectedFiles(files);
    //create new table data var
    let newTableData = [
      ...tableData,
      [
        "itemId",
        "<div style='cursor: pointer;'> = num</div>",
        "<input type='checkbox'>",
        "metaTitle C"
      ]
    ];
    //set table data state 
    console.log('Setting tableData =', newTableData)
    setTableData(newTableData);
  };

So when i drag new files, I can see the state var for tableData got updated because the new third row is printed on the dom for Project.js, but the <Table tableData={tableData} /> line which passes the state var into the Table.js component, does not update the table? Am I updating or passing my state var tableData wrong?
enter image description here

https://codesandbox.io/s/q2-50w1n7?file=/src/Table.js

Regex não funciona quando há uma quebra de linha [closed]

Estou tendo um problema, preciso de um regex que selecione todo o texto que estiver dentro das chaves

Exemplo:

const string = `

Olá! {TESTE}

`;

const regex = /{(.*)}/gm;

const name = string.match(regex);

console.log(name) // {TESTE} como desejado

Mais quando ele quebra de linha ele vem NULL

const string = Olá { TESTE };

const regex = /{(.*)}/gm;

const name = string.match(regex);

console.log(name); // NULL

// Esse e meu regex atual
const regex = /{(.*)}/gm;

Managing more than one slider in HTML

I’m new to html and recognize this may be a basic question. However I haven’t been able to find any examples of this sort of functionality yet. I’m trying to do math with the input from two different sliders. Thus far, my code looks like this:

<html>

<body>
  <h1> Slider Test</h1>

  <div id="myDiv"></div>
  <p> sliderx </p>
  <form oninput="amount.value=rangeInput.value">
    <input type="range" id="rangeInput" name="rangeInput" step="0.05" min="0.0" max="1.0" value="get_min() "
      oninput="sliderx(this.value)">
    <output name="amount" for="rangeInput"></output>
  </form>

  <p> slidery </p>
  <form oninput="amount.value=rangeInput.value">
    <input type="range" id="rangeInput" name="rangeInput" step="0.05" min="0.0" max="1.0" value="get_min() "
      oninput="slidery(this.value)">
    <output name="amount" for="rangeInput"></output>
  </form>

  <script>

    function f(x, y) {
      return x + y
    }

    function sliderx(value) {
      val = f(value, 1.0)
      console.log(val)
    }

  </script>
  </div>
</body>

</html>

I created two sliders (sliderx and slidery) and defined f(x,y) = x+y. My goal is to be able to print x+y to console.log. I can call silderx and my console updates accordingly for fixed y. However, I don’t see any good way to update y using slidery, while keeping x defined by sliderx. Is there any way to do this?

prisma return empty with mongodb even that there is data

I’m learning next 13, and I’m trying to do a simple api request that bring me the data from the database,but I’ve received an empty array back from the database,
I’m trying to achieve this using Prisma

this is my prisma schema:

datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}


generator client {
  provider = "prisma-client-js"
}

model Toy {
  id       String    @id @default(auto()) @map("_id") @db.ObjectId
  name    String
  price     String
  labels   String[]      
  createdAt String    
  inStock Boolean
}


model User {
  id      String   @id @default(auto()) @map("_id") @db.ObjectId
  password   String   
  username    String
  fullName String
  isAdmin   Boolean
}

this is prisma client instense

import { PrismaClient } from '@prisma/client'

const prisma = global.prismadb || new PrismaClient()
if (process.env.NODE_ENV !== 'production') global.prismadb = prisma

export default prisma

this is the database request

export async function GET() {
    try {
        const res = await prisma.toy.findMany()
        const data = await res.json()
        return NextResponse({ data })
    } catch (err) {
        console.log('Error', err)
    }
}

It is return an empty array, but there is data on the database, and even when I try to consoloe.log() the data it is empty array

this is my DATABASE_URL and of course replaced with the username and password:
DATABASE_URL="mongodb+srv://<username>:<password>@cluster0.qplxj.mongodb.net/itemDB

Three.js – ArrowHelper not showing up

I’ve been stuck trying to draw an arrow using THREE.ArrowHelper for multiple hours now, hopefully, someone can shine some light on the issue. My code is as follows:

function draw_an_arrow(name, from, to, color, layer) {
    let direction = to.clone().sub(from)
    let length = direction.length()
    let obj = new THREE.ArrowHelper(direction.normalize(), from, length, color)
    obj.name = name
    obj.layers.set(layer)  
    scene.add(obj)
    return obj
}

The name, from, to, color, and layer are provided function parameters in the correct format. This is verified. The provided layer and scene also work. When drawing anything else within the same function such as a plane, circle, or even line they show up. Since my visualization is 2D, all objects are drawn with z-coordinate 0 and my camera hovers orthogonally over x-y-plane.

The code I am using follows most of the examples I found online to the letter. What am I missing?

Grid.js from HTML Table with RowSelection

I would like to use Grid JS with a HTML table that is already rendered. I would also like to utilize the RowSelection Plugin. How can I do both.

Here is the code I would like to execute.

const grid = new Grid({
            sort: true,
            from: this.tableTarget,
            columns:[
                {
                    id: 'selectRow',
                    name:  html( '<input type="checkbox" name="custom_toggle" class="mx-auto w-100" data-action="click->web--tenant--grid#toggleSelectAll" />' ),
                    width: "95px",
                    sort: false, 
                    plugin: {
                        component: RowSelection,
                    }
                }
            ],
            resizable: true,
            className: {
                table: 'table table-striped'
            },
            style: {
                table: {"white-space": "nowrap"},
            },
            autoWidth: true
        })

Nested Objects into Arrays into an Object

I would need help to access the value of a key-value pair from an object that is itself nested into an array (several objects with 2 key-value pairs inside an array Several arrays into an object).

So for example, I would need to access only one of the names such as Max or Lucas…

I tried to access it but no luck… Any help would be much appreciated.

const nested = {
    40: [
        { hello: "1", name: "Max" },
        { hello: "2", name: "Julie" },
        { hello: "3", name: "Mark" },
        { hello: "4", name: "Isabella" },
    ],
    50: [
        { hello: "1", name: "William" },
        { hello: "2", name: "James" },
        { hello: "3", name: "Lucas" },
        { hello: "4", name: "John" },
    ],
};


// Here is what I tried but I didn't find any way to access a console.log that would return only a // single in the output.


const keysHello = Object.keys(nested);
console.log("keysHello", keysHello); // ['40', '50']

const values = Object.values(nested);
console.log("values", values); // [[{…}, {…}, {…}, {…}], [{…}, {…}, {…}, {…}])]

const keysValues = Object.entries(nested);
console.log("keysValues", keysValues); // [['40', [{…}, {…}, {…}, {…}]], ['50', [{…}, {…}, {…}, {…}]]

// The one below does not work
// const [, , {name}] = nested;
// console.log(`${Object.values[40]}`);

JS Map confusion

Trying to get the data from Array, Received Error. I have passed data into the component
and accessing the data of pizza that is an Array. Please help to solve this mapping
Error. What doing wrong here in mapping ?

const mockJson = {
        
                "pizza": [
                    {
                        "id": 0,
                        "name": "Margherita",
                        "description": "",
                        "ingredients": ["tomato sauce", "mozzarella"],
                        "spicy": false,
                        "vegetarian": true,
                        "price": 17.0,
                        "image": "https://i.imgur.com/8B8YLOo.jpg"
                    },
                    {
                        "id": 1,
                        "name": "Pepperoni",
                        "description": "",
                        "ingredients": ["tomato sauce", "mozzarella", "double pepperoni"],
                        "spicy": false,
                        "vegetarian": false,
                        "price": 20.0,
                        "image": "https://i.imgur.com/OHHctnf.jpg"
                    }
        ]
        
        const RestaurantCard = (data) => {
            console.log(data, 'data1') //data is reachable
         return (
           <>   
            <div className="res-card">
            {console.log(helo, 'data2')} 
              {data.pizza?.map((helo,id) => 
         
              {
              return (
                <p key={id}>{helo.name}</p>
                <p key={id}>{helo.name}</p>
                )
              }
                )}
               
              
            </div>
            </>
            ) 
        }
        
 ================================= 
const Body = () => {
            return (
                <>
                <div className="res-container"><RestaurantCard data={mockJson} />
                </div>
                
                </>
            )
        }

I’m unable to get {helo.name}, what wrong am i doing ?

How do i get data in dynamic routes nextjs 13

the route is simple /Product/Category/id

this is the [id].tsx component

"use client";
import SinglePSlider from "../../../Component/SinglePSlider";
import Navbar from "../../../Navbar/page";
import "../../../globals.css";
import {useEffect, useState} from "react"
import { useSearchParams } from "next/navigation";

interface productItem {
  id?: number;
  name: string;
  image1: string;
  image2: string;
  image3: string;
  image4: string;
  description: string;
  price?: string;
  prices: {
    half: string;
    full: string;
  };
  categories: string;
}

const Item = () => {
  const searchParams = useSearchParams();

  const [product, setProduct] = useState<productItem | null>(null);
  const id = searchParams.get("id");
   useEffect(() => {
     const fetchData = async () => {
       const res = await fetch(`/items.json`);
       const data = await res.json();
       const productItem = data.Cakes.find(
         (item: productItem) => item.id === Number(id)
       );
       setProduct(productItem);
     };

     if (id) {
       fetchData();
     }
   }, [id]);
  return (
    <>
      <Navbar />
      <div className="singleproduct-main">
        <div className="singleproduct-parallex">
          <SinglePSlider
            img1={product?.image1 || ""}
            img2={product?.image2 || ""}
            img3={product?.image3 || ""}
            img4={product?.image4 || ""}
          />
        </div>
        <div className="singleproduct">
          <h4 className="singleproduct-title">{product?.name}</h4>
          <div className="singleproduct-franchise">
            <select>
              <option disabled selected value="">
                Select Franchise
              </option>
              <option value=""></option>
            </select>
          </div>
          <p className="singleproduct-para">{product?.description}</p>
        </div>
      </div>
    </>
  );
};

export default Item;

i tried this but didn’t work.The actual working should be to get the id and find it in the json file and get its data. i used getstaticprops, getstaticpaths but didnt worked out. i console logged the id and it shows null is it because it is string first and when comparing the id its number? . what can be the problem?