Why is the return type of a generic TypeScript function inferred differently for a variable initialization and an assignment?

Given a Typescript function with a generic type that is used for the return type and has a default value, the return type of the function is inferred differently when using the function’s return value to initialize a variable and assigning it to a typed variable.

Here is a simplified example :

function test<T extends Element =  HTMLElement>(elementName:string):T{
  // irrelevant, just returning something
  return document.createElement(elementName) as unknown as T;
}

const e1 = test('div'); // fine, e1's inferred type is HTMLElement
let e2: HTMLElement | undefined;
e2 = test('div'); // Type error

In the first case (e1), everything is fine, the default generic type HTMLElement is used and the type of e1 is inferred to HTMLElement.

In the second case, the type of the return value is inferred to Element and it causes a type error, as Element can’t be assigned to HTMLElement.

Why is the behavior different? Why is the generic default value not used in the second case? Is it expected?

Example in TS playground

Close all other accordions when one is opened

I have the code below which will open and close accordions, I need help if I open one, the rest are closed, my issue with this code is that I can’t close the current opened accordion, if you click on the same accordion it will open, but if you try to click it again it won’t close.

CodePen: [https://codepen.io/C3ISR-Everything-Cybersecurity/pen/azbeOEK]

                const accordionEl = document.querySelector('.main')
const panelEls = accordionEl.querySelectorAll('.panel')

accordionEl.addEventListener('click', ({ target }) => {
  if (target.classList.contains('accordion')) {
    panelEls.forEach(panelEl => {
      panelEl.classList.remove('open')
    })
    
    const { nextElementSibling } = target
    nextElementSibling.classList.add('open')
  }
})
       body {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            background-color: White;
            font-family: Sakkal Majalla;
            direction: rtl;
            position: relative;
            z-index: -2;
            -ms-overflow-style: none;
            
        }
        body::-webkit-scrollbar, body::-webkit-scrollbar-button { display: none; } /* Chrome */


        li {
            list-style: none;
        }

        a {
            text-decoration: none;
        }

        .main{    
            display: grid;
            grid-template-columns: 1fr;
            justify-items: center;
            margin-top: 2rem;
            margin-bottom: 1rem;
        }

        table {
            border: 1px solid #dededf;  
            table-layout: fixed;
            border-collapse: collapse;
            border-spacing: 1px;
            text-align: center;
        }

        th {
            border: 1px solid #dededf;
            background-color: #eceff1;
            color: #000000;
            padding: 5px;
        }

        td {
            border: 1px solid #dededf;
            background-color: #ffffff;
            color: #000000;
            padding: 5px;  
        }
        th:nth-child(1) {  
            width: 30.9rem;
        }

        th:nth-child(2) {  
            width: 10rem;
        }
        th:nth-child(3) {  
            width: 7rem;
        }

        .accordion {
            background-color: #ffffff;
            color: black;
            font-weight: bold;
            cursor: pointer;
            margin-top: 20px;
            padding: 18px;
            border: none;
            text-align: right;
            outline: none;
            font-size: 20px;
            transition: 0.4s;
            width: 50rem;
            border: 1px solid rgb(219, 219, 219);
            border-radius: 8px;
            box-shadow: rgba(100, 100, 111, 0.123) 0px 7px 29px 0px;
        }

        .active, .accordion:hover {
            border-radius: 8px 8px 0px 0px;
            border-color:  rgb(0, 128, 255);
        }

        .accordion span{
            float: left;
            font-size: 15px;
            color: #116ce4;
        }
/* OLD CODE USE BELOW IT
        .panel {
            display: none;
            overflow: hidden;  
        }
*/
.panel {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.5s ease, padding 0.5s ease;
    padding: 0px;
}

.panel.open {
    max-height: 1000px;
    padding: 18px;
}
   <div class="main">
            <button class="accordion">
                John Doe
            </button>
            <div class="panel">
                <table>
                    <th>company</th>
                    <th>department</th>
                    <th>2025?</th>
                    <tr>
                        <td>COMPANY A</td>
                        <td>FINANCE</td>
                        <td>&#9989;</td>
                    </tr>
                    <tr>
                        <td>COMPANY Z</td>
                        <td>PMO</td>
                        <td>&#10060;</td>
                    </tr>
                </table>
            </div>
                 <button class="accordion">
                John Doe
            </button>
            <div class="panel">
                <table>
                    <th>company</th>
                    <th>department</th>
                    <th>2025?</th>
                    <tr>
                         <td>company A</td>
                        <td>HR</td>
                        <td>&#10060;</td>
                    </tr>
                    <tr>
                       <td>company B</td>
                        <td>HR</td>
                        <td>&#10060;</td>
                    </tr>
                    <tr>
                          <td>company C</td>
                        <td>HR</td>
                        <td>&#10060;</td>
                    </tr>
                </table>
            </div>
                 <button class="accordion">
                John Doe
            </button>
            <div class="panel">
                <table>
                    <th>company</th>
                    <th>department</th>
                     <th>2025?</th>
                    <tr>
                        <td>company A</td>
                        <td>HR</td>
                        <td>&#9989;</td>
                    </tr>
                </table>
            </div>       
    </div>

xterm.js Backspace Not Working After Simulated Autocomplete with TAB

I’m building a terminal interface using xterm.js and handling a remote shell via WebSocket. Autocomplete is server-side—when a user types part of a command like sen and presses TAB, the server responds with send .

To simulate this autocomplete, I call a simulateTyping() function that appends the completed part to the terminal and updates the internal buffer (currentInput):

function simulateTyping(text) {
  for (let ch of text) {
    term.write(ch); // visually show char
    socket.send(JSON.stringify({ msg: 'input', body: ch })); // send to server
    currentInput += ch;
    updateGhost();
  }
}

The problem: backspace only deletes the characters the user typed manually. After simulateTyping(), the autocompleted text (send ) becomes “visually” present, but when the user presses backspace, it only removes the characters originally typed (sen)—not the autocompleted portion.

I’ve tried managing currentInput manually and even injecting characters one-by-one, but xterm.js doesn’t seem to treat these as truly typed input.

Here’s part of the socket.on(‘message’) logic that triggers the autocomplete:

if (promptMatch && typedText.startsWith(lastHistory)) {
  const appendText = typedText.slice(lastHistory.length);
  simulateTyping(appendText); // simulate autocomplete
}

❓How can I make autocompleted text deletable like manually typed input in xterm.js?
Is there a way to “trick” xterm.js into treating this input as if typed by the user?

Do I need to feed it differently to the buffer?

Or is there an addon or API pattern I’m missing?

Any help would be appreciated!

Javascript Node.js not working on saving a file

I need a help about my code. I get a field BytesBoleto in a Base64 encoded pdf. I need to filter them from a json and save the pdf files on user desktop. How can I do that? What´s wrong with my code?

I got the error; “The “data” argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of File”

Here is my code:

// Função para decodificar Base64 e criar arquivos PDF
function gerarPDFsDeJson(jsonData) {
    // Verifica se jsonData é um objeto
    if (typeof jsonData !== 'object' || jsonData === null) {
        throw new Error("Entrada inválida: deve ser um objeto JSON.");
    }

    // Array para armazenar os arquivos PDF
    const pdfFiles = [];

    // Função recursiva para percorrer o JSON e encontrar os campos "BytesBoleto"
    function procurarBytesBoleto(obj) {
        for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
                if (key === 'BytesBoleto' && typeof obj[key] === 'string') {
                    // Decodifica a string Base64
                    const byteCharacters = atob(obj[key]);
                    const byteNumbers = new Uint8Array(byteCharacters.length);
                    for (let i = 0; i < byteCharacters.length; i++) {
                        byteNumbers[i] = byteCharacters.charCodeAt(i);
                    }
                    const blob = new Blob([byteNumbers], { type: 'application/pdf' });
                    const pdfFile = new File([blob], `${key}.pdf`, { type: 'application/pdf' });
                    pdfFiles.push(pdfFile);
                } else if (typeof obj[key] === 'object') {
                    procurarBytesBoleto(obj[key]); // Chama a função recursivamente
                }
            }
        }
    }

    procurarBytesBoleto(jsonData);
    return pdfFiles;
}

// Function to save PDF files to desktop
function savePDFsToDesktop(buffers, keys) {
    const desktopPath = path.join(require('os').homedir(), 'Desktop'); // Get user's desktop path

    buffers.forEach((buffer, index) => {
        const filePath = path.join(desktopPath, `${keys[index]}.pdf`);
        fs.writeFile(filePath, buffer, (err) => {
            if (err) {
                console.error(`Error saving ${keys[index]}.pdf:`, err);
            } else {
                console.log(`Successfully saved ${keys[index]}.pdf to ${desktopPath}`);
            }
        });
    });
}

// Function to save files
const fs = require('fs');
const path = require('path');
// Assuming you have an array of Buffer data and keys for the PDF files
const keys = ['file1', 'file2']; // Corresponding keys for file names

// Exemplo de uso
const jsonExample = {
    documentos: [
        { BytesBoleto: "JVBERi0xLjQKJeLjz9MKNCAwIG9iaiA8PC9Qcm9jU2V0IDggMCBSIC9FbmNvZGluZyA8PC9MZW5ndGggNjY1ID4+PgplbmRvYmoK" },
        { BytesBoleto: "JVBERi0xLjQKJeLjz9MKNCAwIG9iaiA8PC9Qcm9jU2V0IDggMCBSIC9FbmNvZGluZyA8PC9MZW5ndGggNjY1ID4+PgplbmRvYmoK" },
    ]
};

const pdfFilesArray = gerarPDFsDeJson(jsonExample);
console.log(pdfFilesArray); // Aqui você terá um array de arquivos PDF

// Call the function to save the PDFs
savePDFsToDesktop(pdfFilesArray, keys);

Thanks for the help

How To Build An Object or Array With Unique Key Names From Unique Array Object Values With All Array Items With Said Unique Key Name [duplicate]

I would like to produce an array (plus, separately, an object, if possible) from the unique ‘custRef’ values in the following array:

[
  {
    "id": 1233,
    "custRef": "ABC1234",
    "somethingElse": 10.0,
    "someRef": "37856394943222"
  },
  {
    "id": 1234,
    "custRef": "ABC1235",
    "somethingElse": 11.0,
    "someRef": "37856394943222"
  },
  {
    "id": 1235,
    "custRef": "ABC1235",
    "somethingElse": 13.0,
    "someRef": "3498537945734567"
  }
]

Preferred results:

I would like to produce this array:

[
  {
    "custRef": "ABC1234",
    "items": [
      {
        "id": 1233,
        "custRef": "ABC1234",
        "somethingElse": 10.0,
        "someRef": "37856394943222"
      }
    ]
  },
  {
    "custRef": "ABC1235",
    "items": [
      {
        "id": 1234,
        "custRef": "ABC1235",
        "somethingElse": 11.0,
        "someRef": "37856394943222"
      },
      {
        "id": 1235,
        "custRef": "ABC1235",
        "somethingElse": 13.0,
        "someRef": "3498537945734567"
      }
    ]
  }
]

… and additionally, if possible, this object:

{
  "ABC1234": [
    {
      "id": 1233,
      "custRef": "ABC1234",
      "somethingElse": 10.0,
      "someRef": "37856394943222"
    }
  ],
  "ABC1235": [
    {
      "id": 1234,
      "custRef": "ABC1235",
      "somethingElse": 11.0,
      "someRef": "37856394943222"
    },
    {
      "id": 1235,
      "custRef": "ABC1235",
      "somethingElse": 13.0,
      "someRef": "3498537945734567"
    }
  ]
}

I assume that this would be some kind of combination of .filter() and .map (or maybe .reduce()) but I don’t really know what I’m doing, and so don’t really know what I am supposed to be looking for.

Assuming that I plop the above source array into a variable named ‘orderItems‘ I have managed to produce a simple array of the unique ‘custRef‘ values, with the below javascript. However, I’m failing to find a way use that effectively … or knowing if I should be using it at all?

var uniqueOrdersWtItms = Object.keys(orderItems.reduce((r,{oh_cust_order_ref}) => (r[oh_cust_order_ref]='', r) , {}));

Like I say, I can’t stress this enough, I don’t really know what I need to look for, so whilst I have tried to build this through any number of search results both here and elsewhere … it’s hard to know what to ask for. If anyone can help, that’d be amazing.

stackoverflow’s suggestion gave this answer:
Creating new array with unique key while mapping through given array
But it doesn’t seem to do what I want, or I cannot understand it well enough. 🙁

How to use getStaticProps in app/ Page component

I think that Page.tsx belongs to app/.

In src/app/Page.tsx, the MRE:

export default function Home({ images: { poze } }: {
  images: {
    poze: string;
  }
}) {
  return poze;
};

export const revalidate = 60;
export const dynamicParams = true;

export const getStaticProps = async () => {
  return {
    props: {
      images: {
        poze: "abc",
      }
    },
  };
};

Expected: “abc” is displayed.

Error:

./src/app/page.tsx
Error:   × "getStaticProps" is not supported in app/. Read more: https://nextjs.org/docs/app/building-your-application/data-fetching
  │ 
  │ 
    ╭─[/home/silviub/Desktop/Pro/home-gh-pages/src/app/page.tsx:12:1]
  9 │ export const revalidate = 60;
 10 │ export const dynamicParams = true;
 11 │ 
 12 │ export const getStaticProps = async () => {
    ·              ──────────────
 13 │   return {
 14 │     props: {
 15 │       images: {
    ╰────

The link in the error did not help. The original relevant SSG source is here.

Populating elements live when events happen not happening

I have the following template with two dropdowns. When an item is selected in the first dropdown it dynamically populates the second. It works, but not how I would expect. It takes a couple selections for the second select to populate.

<select class="select input input-bordered" (change)="onStudentChange($event)" >
        <option disabled selected value="0">Choose Student</option>
        <option *ngFor="let student of studentsByUser$ | async" value="{{student._id}}">{{ student.name }}</option>
      </select>
      <select *ngIf="selectedStudentId != ''" class="select input input-bordered" (change)="onMonthChange($event)" >
        <option disabled selected>Choose Month</option>
        <option *ngFor="let month of months" value="{{month}}">{{month}}</option>
      </select>

Here is the event:

onStudentChange(event: any): void {
    this.selectedStudentId = event.target.value;
    // Get the available months with published meals for selected student
    this.studentsByUser$.subscribe((students) => {
      const selectedStudent = students.find((student) => student._id === this.selectedStudentId);
      this.mealService.getMealsBySchool(selectedStudent?.school?._id!).subscribe((meals) => {
        const months: string[] = [];
        meals.map(meal => meal.date).map((dateString) => {
          months.push(new Date(dateString).getFullYear() + '-' + new Date(dateString).getMonth());
        })
        this.months = months
      });

    });
  }

this.months is getting the current values on debugging, but not reflected in the UI until the event is called again

Regex – get comma if it does not have an escaped quote at some point in front of it

I’m struggling with a regex expression. I have a string like this:

700,"some text, and more text",False,0000000000,text,"806,474.72"

And I need to split it into fields by commas, unless the comma is preceded by an escaped quote. The desired output is:

[0] 700
[1] Some text, and more text
[2] False
[3] 0000000000
[4] text
[5] 806,474.72

What would be the right Regex expression for this?

Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response, with chrome extension

enter image description here

I’m working on a chrome devtools panels extension. In it I have:

const toDbBtn = document.getElementById("toDbBtn");

toDbBtn.addEventListener("click", async () => {
  const dbName = document.getElementById("textBox").value;

  // const result = await chrome.storage.local.get(["yourKey"]);

  const storedJSON = await chrome.storage.local.get(["yourKey"]);
  console.log("Result from storage:", storedJSON);

  if (storedJSON.yourKey) {

    const parsedArray = JSON.parse(storedJSON.yourKey);
    console.log("Parsed Array:", parsedArray);
    const partArray = parsedArray.slice(0, 30);
    console.log("partArray", partArray);
    const data = {
      dbName: dbName,
      savedArray: partArray,
    };

    const postable = JSON.stringify(data);
    console.log("postable", postable);
    // http://localhost:8888/.netlify/functions//updateCollection.js

    const response = await fetch(
      "http://localhost:8888/.netlify/functions/updateCollection",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          // "Access-Control-Allow-Origin": "*",
          // "Access-Control-Allow-Methods": "POST",
          // "Access-Control-Allow-Headers": "Content-Type",
        },
        body: postable,
      }
    );

    const result = await response.json();
    console.log("Response from server:", result);
  } else {
    console.log("Value not found in storage for key: yourKey");
  }
});

I’m planning to send some data to a netlify function, and so decided to test locally using “NTL DEV” command.

my target function is:

const headers = {
  "Cache-Control": "no-cache",
  "Cross-Origin-Opener-Policy": "unsafe-none",
  "Cross-Origin-Embedder-Policy": "unsafe-none",
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Private-Network": "true",
  "Access-Control-Allow-Headers": "Access-Control-Request-Private-Network",
  "Access-Control-Allow-Methods": "OPTIONS,POST,GET,HEAD,QUERY,query",
};

exports.handler = async function (event, context) {

  console.log("context: ", context);
  console.log("event: ", event);

  if (event.httpMethod !== "OPTIONS" && event.httpMethod !== "POST") {
    console.log("event.httpMethod: ", event.httpMethod);
    return {
      statusCode: 405,
      body: JSON.stringify({ message: "Method Not Allowed" }),
    };
  } else if (event.httpMethod === "OPTIONS") {
    return {
      statusCode: 204,
      headers: headers,
      body: null,
    };
    
  } 
  if (event.httpMethod === "POST") {
    console.log("event.httpMethod: ", event.httpMethod);
    console.log("event.body: ", event.body);
    const data = JSON.parse(event.body);
    console.log("data: ", data);
  }

I’m getting the error in the title .What am I doing wrong?

How do I optimize my code for Climbing the Leaderboard on Hackerrank using JavaScript? [closed]

I used a Binary Search implementation and caching to try to solve the problem, but I still can’t pass two test cases: 6 and 8. Any help on what I should do next would greatly be appreciated.

My code is as follows:

function climbingLeaderboard(ranked, player) {
    // Write your code here
    
    ranked = [...new Set(ranked)]
    
    let cache = {};
    
    
    let finalRank = player.map((p) => {
        
        let first = 0;
        let last = ranked.length - 1;
        
        if (cache[p]) {
            return cache[p];
        }
        
        
        
        while (first <= last) {
            let mid = first + Math.floor((last - first)/2);
            console.log("Made It!")
            
            console.log(`mid: ${mid}, p: ${p}`)
            
            if (ranked[mid] == p) {
                cache[p] = mid + 1;
                return mid + 1;
            }else if (ranked[mid] < p) {
                last = mid - 1;
            }else {
                first = mid + 1;
            }
        }
        
        cache[p] = first + 1;
        return first + 1;
    });
    
    return finalRank;

}

For reference, I previously tried turning the map function into a for loop but that made me fail all my tests, so I reverted back to the map function.

How to use useState without “use client” in Next.js when I use generateStaticParams

I need this in an SSG to send to photo galleries the image files’ dimensions. I expected no error.

Error of “npm run dev”:

21:23:44 ~/Desktop/Pro/home-gh-pages main $ npm run dev

> [email protected] dev
> next dev

   ▲ Next.js 15.2.5
   - Local:        http://localhost:3000
   - Network:      http://192.168.1.100:3000

 ✓ Starting...
 ✓ Ready in 1593ms
 ○ Compiling / ...
 ⨯ ./src/app/page.tsx
Error:   × You're importing a component that needs `useState`. This React hook only works in a client component. To fix, mark the file (or its parent) with the `"use client"` directive.
  │ 
  │  Learn more: https://nextjs.org/docs/app/api-reference/directives/use-client
  │ 
  │ 
    ╭─[/home/silviub/Desktop/Pro/home-gh-pages/src/app/page.tsx:14:1]
 11 │ import Thumbnails from "yet-another-react-lightbox/plugins/thumbnails";
 12 │ import Zoom from "yet-another-react-lightbox/plugins/zoom";
 13 │ import "yet-another-react-lightbox/plugins/thumbnails.css";
 14 │ import { useState } from "react";
    ·          ────────
 15 │ 
 16 │ import LiteYouTubeEmbed from 'react-lite-youtube-embed';
 17 │ import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css';
    ╰────

Import trace for requested module:
./src/app/page.tsx
 ⨯ ./src/app/page.tsx
Error:   × You're importing a component that needs `useState`. This React hook only works in a client component. To fix, mark the file (or its parent) with the `"use client"` directive.
  │ 
  │  Learn more: https://nextjs.org/docs/app/api-reference/directives/use-client
  │ 
  │ 
    ╭─[/home/silviub/Desktop/Pro/home-gh-pages/src/app/page.tsx:14:1]
 11 │ import Thumbnails from "yet-another-react-lightbox/plugins/thumbnails";
 12 │ import Zoom from "yet-another-react-lightbox/plugins/zoom";
 13 │ import "yet-another-react-lightbox/plugins/thumbnails.css";
 14 │ import { useState } from "react";
    ·          ────────
 15 │ 
 16 │ import LiteYouTubeEmbed from 'react-lite-youtube-embed';
 17 │ import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css';
    ╰────

Import trace for requested module:
./src/app/page.tsx
 ⨯ ./src/app/page.tsx
Error:   × You're importing a component that needs `useState`. This React hook only works in a client component. To fix, mark the file (or its parent) with the `"use client"` directive.
  │ 
  │  Learn more: https://nextjs.org/docs/app/api-reference/directives/use-client
  │ 
  │ 
    ╭─[/home/silviub/Desktop/Pro/home-gh-pages/src/app/page.tsx:14:1]
 11 │ import Thumbnails from "yet-another-react-lightbox/plugins/thumbnails";
 12 │ import Zoom from "yet-another-react-lightbox/plugins/zoom";
 13 │ import "yet-another-react-lightbox/plugins/thumbnails.css";
 14 │ import { useState } from "react";
    ·          ────────
 15 │ 
 16 │ import LiteYouTubeEmbed from 'react-lite-youtube-embed';
 17 │ import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css';
    ╰────

Import trace for requested module:
./src/app/page.tsx
 ⨯ ./src/app/page.tsx
Error:   × You're importing a component that needs `useState`. This React hook only works in a client component. To fix, mark the file (or its parent) with the `"use client"` directive.
  │ 
  │  Learn more: https://nextjs.org/docs/app/api-reference/directives/use-client
  │ 
  │ 
    ╭─[/home/silviub/Desktop/Pro/home-gh-pages/src/app/page.tsx:14:1]
 11 │ import Thumbnails from "yet-another-react-lightbox/plugins/thumbnails";
 12 │ import Zoom from "yet-another-react-lightbox/plugins/zoom";
 13 │ import "yet-another-react-lightbox/plugins/thumbnails.css";
 14 │ import { useState } from "react";
    ·          ────────
 15 │ 
 16 │ import LiteYouTubeEmbed from 'react-lite-youtube-embed';
 17 │ import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css';
    ╰────

Import trace for requested module:
./src/app/page.tsx
 GET / 500 in 326ms

If I use “use client” page.tsx (tested from new index.tsx too) I get error:

21:33:49 ~/Desktop/Pro/home-gh-pages main $ npm run dev

> [email protected] dev
> next dev

   ▲ Next.js 15.2.5
   - Local:        http://localhost:3000
   - Network:      http://192.168.1.100:3000

 ✓ Starting...
 ✓ Ready in 1627ms
 ○ Compiling /_not-found ...
 ✓ Compiled /_not-found in 1323ms (660 modules)
 ⚠ Fast Refresh had to perform a full reload due to a runtime error.
 GET /_next/static/webpack/93bd01d6b78ae12e.webpack.hot-update.json 404 in 1595ms
 ⨯ [Error: Page "/page" cannot use both "use client" and export function "generateStaticParams()".]
 ○ Compiling /_error ...
 ✓ Compiled /_error in 788ms (989 modules)
 GET / 500 in 1194ms

Minimum, reproducible example: page.tsx:

"use client";

import { useState } from "react";

export default function Home() {
  const [x, setX] = useState(-1);
  return <p onClick={() => {
    setX(x + 1);
  }}>{x}</p>;
}

export const revalidate = 60;
export const dynamicParams = true;

export const generateStaticParams = async () => {
  return { data: 100 };
};

Throws Error: Page "/page" cannot use both "use client" and export function "generateStaticParams()".

how can i remove percentage from vue url

how do i remove the % from my url

this what my url returns

http://localhost:8080/product/We-Vibe%2520Sync%2520O%2520Remote%2520and%2520App%2520Controlled%2520Rechargeable%2520latern's

when i click this

   goToProduct(productTitle) {
      console.log("Product Title:", productTitle);
      this.$router.push({
        name: "ProductDetails",
        params: { title: productTitle }, // Pass raw title directly to URL
      });
    },

this how i get the data

    try {
      const productTitle = this.$route.params.title;
      const response = await axios.get(
        `https://ve.onrender.com/api/products/${encodeURIComponent(
          productTitle
        )}`
      );

      this.product = response.data.product || {};
    } catch (error) {
     
    }

this how the backend meant to get the data We-Vibe Sync O Remote and App Controlled Rechargeable latern's

so how do i remove the % from the url without altering the data sent to the backend

Criação de library em react [closed]

Oi, estou com uma dúvida, no meu trabalho eu preciso fazer uma lib em react, que vai consumir relatório, e devolver um dashboard, eu tenho uma api em node.js que gera relatórios com base no aggregate então eu envio um post no insomnia com o header com as labels e nome de cada coluna que transforma em base64 pra formar um pdf ou xls, daí estava precisando fazer uma lib pra consumir eles e transformar em dashboards, no caso é a empresa que eu trabalho que precisa, eles já possuem o front end deles em react.js, só que não possuem os dashboards, então eu precisaria criar essa lib que consome uma api, que recebe um endpoint post, com o headers no body do json aí sim geraria o relatório em base 64, um exemplo de um post que eu faco no json do body na porta post http://localhost:5000/report/:report, eu acho que a lib não precisa enviar um post, mas receber o json desse body do post, mesmo que eu tenha que colocar manualmente, pois eu possuo mais de um relatório e dependendo o json desse body muda, em vez de colocar um json, a minha api de relatório gera um código em base64, que seria o relatório, será que teria como pegar essa base64 e transformar num dashboard?

How to animate Table display: none / block? [duplicate]

CodePen: https://codepen.io/C3ISR-Everything-Cybersecurity/pen/azbeOEK

what I’m trying to do is to have a little bit of animation or transition reveal when the user clicks on the accordion to display the table, full code below HTML CSS JS, I want to animate the open and close transition of the tables under accordion.

Full Code:

HTML:

            var acc = document.getElementsByClassName("accordion");
            var i;

            for (i = 0; i < acc.length; i++) {
                acc[i].addEventListener("click", function() {
                    this.classList.toggle("active");
                    var panel = this.nextElementSibling;
                    if (panel.style.display === "block") {
                        panel.style.display = "none";
                    } else {
                        panel.style.display = "block";
                    }
                });
            }
       body {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            background-color: White;
            font-family: Sakkal Majalla;
            direction: rtl;
            position: relative;
            z-index: -2;
            -ms-overflow-style: none;
            
        }
        body::-webkit-scrollbar, body::-webkit-scrollbar-button { display: none; } /* Chrome */


        li {
            list-style: none;
        }

        a {
            text-decoration: none;
        }

        .main{    
            display: grid;
            grid-template-columns: 1fr;
            justify-items: center;
            margin-top: 2rem;
            margin-bottom: 1rem;
        }

        table {
            border: 1px solid #dededf;  
            table-layout: fixed;
            border-collapse: collapse;
            border-spacing: 1px;
            text-align: center;
        }

        th {
            border: 1px solid #dededf;
            background-color: #eceff1;
            color: #000000;
            padding: 5px;
        }

        td {
            border: 1px solid #dededf;
            background-color: #ffffff;
            color: #000000;
            padding: 5px;  
        }
        th:nth-child(1) {  
            width: 30.9rem;
        }

        th:nth-child(2) {  
            width: 10rem;
        }
        th:nth-child(3) {  
            width: 7rem;
        }

        .accordion {
            background-color: #ffffff;
            color: black;
            font-weight: bold;
            cursor: pointer;
            margin-top: 20px;
            padding: 18px;
            border: none;
            text-align: right;
            outline: none;
            font-size: 20px;
            transition: 0.4s;
            width: 50rem;
            border: 1px solid rgb(219, 219, 219);
            border-radius: 8px;
            box-shadow: rgba(100, 100, 111, 0.123) 0px 7px 29px 0px;
        }

        .active, .accordion:hover {
            border-radius: 8px 8px 0px 0px;
            border-color:  rgb(0, 128, 255);
        }

        .accordion span{
            float: left;
            font-size: 15px;
            color: #116ce4;
        }

        .panel {
            display: none;
            overflow: hidden;  
        }
   <div class="main">
            <button class="accordion">
                John Doe
            </button>
            <div class="panel">
                <table>
                    <th>company</th>
                    <th>department</th>
                    <th>2025?</th>
                    <tr>
                        <td>COMPANY A</td>
                        <td>FINANCE</td>
                        <td>&#9989;</td>
                    </tr>
                    <tr>
                        <td>COMPANY Z</td>
                        <td>PMO</td>
                        <td>&#10060;</td>
                    </tr>
                </table>
            </div>
                 <button class="accordion">
                John Doe
            </button>
            <div class="panel">
                <table>
                    <th>company</th>
                    <th>department</th>
                    <th>2025?</th>
                    <tr>
                         <td>company A</td>
                        <td>HR</td>
                        <td>&#10060;</td>
                    </tr>
                    <tr>
                       <td>company B</td>
                        <td>HR</td>
                        <td>&#10060;</td>
                    </tr>
                    <tr>
                          <td>company C</td>
                        <td>HR</td>
                        <td>&#10060;</td>
                    </tr>
                </table>
            </div>
                 <button class="accordion">
                John Doe
            </button>
            <div class="panel">
                <table>
                    <th>company</th>
                    <th>department</th>
                     <th>2025?</th>
                    <tr>
                        <td>company A</td>
                        <td>HR</td>
                        <td>&#9989;</td>
                    </tr>
                </table>
            </div>       
    </div>