NextJS – Update table content on selecting tabs

I have a table that the content need to be filtered by status tabs (‘new’, ‘on process’, ‘delivered’, etc) usually i’m using useEffect to catch this status tabs selection, and useState to update the table data, but now i have issues where the state is updating (by logging the ‘tableData’ content just after i call setTableData) but the table still on previous ‘tableData’ state.. can you guys tell me where is the problem?

export const OrdersTab = (tabsData : any) => {
// console.log(tabsData);
const [activeTab, setActiveTab] : any = useState(null);
const [activeStatusTab, setActiveStatusTab] : any = useState();
const [tableData, setTableData]:any[] = useState([]);
const [loading, setLoading] = useState(false);

// console.log(tabsData);

useEffect(() => {
    
        if (activeStatusTab) {
            let filteredOrderes = tabsData.initTableData;
            // console.log(filteredOrderes);
            if (activeStatusTab == 'all') {
                filteredOrderes = tabsData.initTableData;
            } else {
                filteredOrderes = filteredOrderes.filter((orders:any) => 
                    orders.status.toString().toLowerCase().includes(activeStatusTab.toLowerCase())
                );
            }
            // console.log(filteredOrderes.length);
            setTableData(filteredOrderes);
            console.log(tableData.length); /* <<-- checking if state updating/not */
        }
}, [activeStatusTab]);

let statusTabs = [
    {
      id: "all",
      label: "All"
    },
    {
      id: "new",
      label: "New"
    },
    {
      id: "process",
      label: "On Process"
    },
    {
      id: "delivery",
      label: "Delivery"
    },
    {
      id: "completed",
      label: "Completed"
    },
    {
      id: "canceled",
      label: "Canceled"
    },
    {
      id: "failed",
      label: "Failed"
    },
];
return (
    <Card>
        <CardBody>
            <div className="flex w-full flex-col">
                <Tabs aria-label="Dynamic tabs" 
                    onSelectionChange={(tabKey) => setActiveTab(tabKey)}
                    fullWidth={true} 
                    items={tabsData.tabsData} >
                    {(item:any) => (
                    <Tab key={item.id} title={item.name}>
                        <Tabs aria-label="Options" onSelectionChange={(statusKey) => setActiveStatusTab(statusKey)} fullWidth={true} items={statusTabs}>
                            {(item) => (
                            <Tab key={item.id} title={item.label}>
                                    <Table id="tablexxx" aria-label="Example empty table">
                                        <TableHeader>
                                            <TableColumn>Product(s)</TableColumn>
                                            <TableColumn>Date</TableColumn>
                                            <TableColumn>Store</TableColumn>
                                            <TableColumn>Status</TableColumn>
                                            <TableColumn>Total Amount</TableColumn>
                                            <TableColumn>Courier</TableColumn>
                                            <TableColumn>Action</TableColumn>
                                        </TableHeader>
                                        {(tableData.length > 0) ? (
                                            <TableBody>
                                                {tableData.map((item:any) => (
                                                    <TableRow key={item.invoice}>
                                                        <TableCell>
                                                            <Link href={'/orders/' + item.id}>
                                                                {item.products[0].main_product.name}
                                                                <p className="text-default-400">SKU: {item.products[0].main_product.sku} x {item.products[0].qty}</p>
                                                                <p className="text-default-400">Invoice: {item.invoice}</p>
                                                            </Link>
                                                        </TableCell>
                                                        <TableCell>{item.createdAt.split('T')[0]}</TableCell>
                                                        <TableCell>{item.store.name}</TableCell>
                                                        <TableCell>{item.status}</TableCell>
                                                        <TableCell>{item.total_amount}</TableCell>
                                                        <TableCell>{item.logistic.name}</TableCell>
                                                        <TableCell>
                                                            {<Dropdown>
                                                                <DropdownTrigger>
                                                                    <Button 
                                                                    variant="bordered"
                                                                    isIconOnly  
                                                                    >
                                                                        <svg className="bi bi-three-dots-vertical" fill="currentColor" height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="M9.5 13a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0zm0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0zm0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0z"/></svg>
                                                                    </Button>
                                                                </DropdownTrigger>
                                                                <DropdownMenu aria-label="Static Actions">
                                                                    <DropdownItem key="new">View</DropdownItem>
                                                                    <DropdownItem key="copy"><Link href={"/orders/" + item.id}>Process</Link></DropdownItem>
                                                                    <DropdownItem key="delete" className="text-danger" color="danger">
                                                                    Reject
                                                                    </DropdownItem>
                                                                </DropdownMenu>
                                                            </Dropdown>}
                                                        </TableCell>
                                                    </TableRow>
                                                ))}
                                            </TableBody>
                                        ) : (
                                            <TableBody emptyContent={"No rows to display."}>{[]}</TableBody>
                                        )} 
                                        
                                    </Table>
                            </Tab>
                            )}
                        </Tabs>
                    </Tab>
                    )}
                    
                </Tabs>
            </div>  
        </CardBody>
    </Card>
)}

Swagger can’t seem to reference model when using examples (multiple example)

How do i reference my models when trying to use multiple example using model/DTO?

@ApiExtraModels(DeliveryOrderListOkDTO, DeliveryOrderListOk2DTO)
@ApiOkResponse({
  content: {
    'application/json': {
      examples: {
        exampleOne: {
          $ref: getSchemaPath(DeliveryOrderListOkDTO),
        },
        exampleTwo: {
          $ref: getSchemaPath(DeliveryOrderListOk2DTO),
        },
        exampleThree: {
          value: {
            message: 'Works fine without ref',
          },
        },
      },
    },
  },
})
// ...

Output:

Example one

Example two

Example three

Generated Swagger/OpenAPI 3.0 Schema:

Paths

Schemas

How am i suppose to use the $ref variable from the source code?:

Documentation

How to update SQL using AJAX and POST with data obtained from a script?

Greetings colleagues I have a query since the truth I have not been able to make this code work, it is a small javaScript that gets a TRM of a coin, everything works well up to that point, what I want to do is update a row called “rate” in the “currencies” table which is in the “id = 1” every time you visit the page and you get the TRM, use the fetch method to send the TRM value to PHP using AJAX and the server will process the request and thus update the database but it does not work, I have all the correct database connection data but something is missing, could you help me please !

<?php 
require 'datab.php'; 
$outPut=array(); 

if ($conexion) { 
    try { 
        if ($_POST['rate']) {
            $rate = $_POST['rate'];
            $datos_trm = "UPDATE currencies SET rate = ? WHERE id = 1 LIMIT 1"; 
            $stmt = $conexion->prepare($datos_trm); 
            $stmt->bind_param("s", $rate); 
            $stmt->execute(); 
            $outPut['datos_trm']=$stmt->affected_rows; 
            $stmt=null; 
            $conexion=null; 
            echo json_encode($outPut);
        }
    } catch (mysqli_sql_exception $e) { 
        echo $e->__toString(); 
    } 
} else { 
    echo 'No hay conexión a la BD'; 
} 
?>
<html lang="es"> 
<body> 
    <div id="rate"></div> 

    <script> 
    const url = "https://www.datos.gov.co/resource/mcec-87by.json?$limit=1"; 
    const request = new Request(url); 

    fetch(request) 
    .then(response => { 
        if (response.status === 200) { 
            return response.json(); 
        } 
    }) 
    .then(json => { 
        const rate = json[0]; 
        if (rate !== undefined && rate.valor !== undefined) { 
            const value = new Number(rate.valor).toFixed(2); 
            document.getElementById("rate").innerText = value.replace('.', ','); 

            // Enviar el valor del TRM a PHP mediante AJAX 
            fetch('', { 
                method: 'POST', 
                headers: { 
                    'Content-Type': 'application/json' 
                }, 
                body: JSON.stringify({ rate: value }) 
            }) 
            .then(response => response.json()) 
            .then(data => console.log(data)) 
            .catch(error => console.error('Error:', error)); 
        } 
    }) 
    .catch(_ => { 
        document.getElementById("rate").innerText = "..."; 
    }); 
    </script> 
</body> 
</html>

Game Board Boundaries Using Random x y coordinates Javascript

My am on the Last part of this game and stuck if I place the ships my self they fit of course but I am using Math.floor(Math.Random() * 10) to get the x,y coords. The ships gets placed on the edges and go offbound often or through a weird undefined error. I have tried returning the function to itself to auto generate a different x,y and changing the path of array[y+i][x] to array[y-i][x] and so on with no good effect so far. I also added a sample of what calls the code.

My github is https://github.com/jsdev4web/battleship
If the randomDir() placeships are uncommmented and the ones with numbers get commentted out is the reflection

The 3 cases are a undefined that breaks the function or code that still goes above 9 or it works perfect

Here is the code:

let [kX, kY, lX, lY, mX, mY, nX, nY, oX, oY] = Array.from({ length: 10 }, () => Math.floor(Math.random() * 10))
let [pX, pY, qX, qY, rX, rY, sX, sY, tX, tY] = Array.from({ length: 10 }, () => Math.floor(Math.random() * 10))

    //cpu.placeShip(kX,kY,chaser,"vertical")
    //cpu.placeShip(lX,lY,seeker,"vertical")
    //cpu.placeShip(mX,mY,longride,"horizontal")
    //cpu.placeShip(nX,nY,underwater,"horizontal")
    //cpu.placeShip(oX,oY,toofast,"vertical")
placeShip(x, y, ship, direction){
        //what i searched -- place a vertical object on a 2D array javascript
        let array = this.board
        //console.log(array)
        let length = array.length
        //console.log(length)

        if(x < 0 || x >= length || y < 0 || y >= length){
            return "Out of bounds"
        }

        let len = ship.length

        //Here i push a obj list of ships each player
        this.playerShips.push(ship)
        
        x = x-1
        y = y-1

        //add a if statement to stop off the board
        if(direction === "horizontal"){
            for(let i = 0; i < len; i++){
                
                array[y][x+i] = "S";
                this.queue.push(`${y}-${x+i}`)
                ship.coords.push(`${y}-${x+i}`)
                
            }
        }else if (direction === "vertical"){
            for(let i = 0; i < len; i++){
                
                array[y+i][x] = "S";
                this.queue.push(`${y+i}-${x}`)
                ship.coords.push(`${y+i}-${x}`)
            }
        }
        return array
    }placeShip(x, y, ship, direction){
        //what i searched -- place a vertical object on a 2D array javascript
        let array = this.board
        //console.log(array)
        let length = array.length
        //console.log(length)

        if(x < 0 || x >= length || y < 0 || y >= length){
            return "Out of bounds"
        }

        let len = ship.length

        //Here i push a obj list of ships each player
        this.playerShips.push(ship)
        
        x = x-1
        y = y-1

        //add a if statement to stop off the board
        if(direction === "horizontal"){
            for(let i = 0; i < len; i++){
                
                array[y][x+i] = "S";
                this.queue.push(`${y}-${x+i}`)
                ship.coords.push(`${y}-${x+i}`)
                
            }
        }else if (direction === "vertical"){
            for(let i = 0; i < len; i++){
                
                array[y+i][x] = "S";
                this.queue.push(`${y+i}-${x}`)
                ship.coords.push(`${y+i}-${x}`)
            }
        }
        return array
    }
    ```
    

sort and search functionality not working together

i have the following search and sort functions in my javascript file and the following html file

Javascript file

document.addEventListener('DOMContentLoaded', function() {
  const csrfToken     = document.getElementsByName('csrfmiddlewaretoken')[0]?.value;
  const resultsListFW = document.getElementById('list-results-fw');
  const listFW        = document.getElementById('list-fw');
  const searchInputFW = document.getElementById('search-input-fw');

  function renderFWData(data) {
    resultsListFW.innerHTML = ''; // Clear previous results

    let counter = 1;

    data.forEach(item => {
      const row = 
       `<tr>
          <td>${counter}</td>
          <td>${item.customer}</td>
          <td><a href="detail/${item.pk}" target="_blank">${item.name}</a></td>
        </tr>
        `;
      resultsListFW.insertAdjacentHTML('beforeend', row);
      counter++;
    });
    listFW.classList.add('not-visible');
    resultsListFW.classList.remove('not-visible');
  }

  function performFWSearch(query) {  // FW: Perform search
    fetch('/fw_search', {
        method: 'POST',
        headers: {
          'X-Requested-With' : 'XMLHttpRequest',
          'Content-Type'     : 'application/x-www-form-urlencoded',
          'X-CSRFToken'      : csrfToken
          },
        body: new URLSearchParams({
          fw: query
        })
      })
      .then(response => response.json())
      .then(data => {
        renderFWData(data.data);
      })
      .catch(error => {
        console.log('Error fetching FW data:', error);
      });
  }
});


document.addEventListener('DOMContentLoaded', () => {
  const table   = document.getElementById('fw-table');
  const headers = table.querySelectorAll('th[data-sort]');
  const tbody   = table.querySelector('tbody');

  headers.forEach(header => {
    header.addEventListener('click', () => {
      const sortKey = header.getAttribute('data-sort');
      const rows = Array.from(tbody.querySelectorAll('tr'));

      // Determine sorting order
      const order = header.dataset.order === 'asc' ? 'desc' : 'asc';
      header.dataset.order = order;

      // Sort rows
      rows.sort((a, b) => {
        const aText = a.querySelector(`td:nth-child(${header.cellIndex + 1})`).textContent.trim();
        const bText = b.querySelector(`td:nth-child(${header.cellIndex + 1})`).textContent.trim();

        if (!isNaN(aText) && !isNaN(bText)) {
          // Numeric comparison
          return order === 'asc' ? aText - bText : bText - aText;
        } else {
          // String comparison
          return order === 'asc' ? aText.localeCompare(bText) : bText.localeCompare(aText);
        }
      });

      // Append sorted rows to tbody
      rows.forEach(row => tbody.appendChild(row));
    });
  });
});

And the following html file

<div class="card">
  <div class="card-header">
    <div class="card-tools">
      <!-- Search Form -->
      <form id="search-form-fw" method="get" action="" autocomplete="off">
        {% csrf_token %}
        <input type="text" id="search-input-fw" name="search" placeholder="Search">
        <button type="submit" class="btn btn-primary btn-sm">Search</button>
      </form>
    </div>
    <button type="button" class="btn btn-tool mt-0" data-card-widget="collapse" title="Collapse">
            <i class="fas fa-minus"></i>
        </button>
  </div>
  <div id="fw-wrapper" class="dataTables_wrapper dt-bootstrap4">
    <div class="row">
      <div class="col-sm-12 col-md-6"></div>
      <div class="col-sm-12 col-md-6"></div>
    </div>
    <div class="row">
      <div class="col-sm-12">
        <table class="table table-bordered table-hover dataTable dtr-inline" id="fw-table">
          <thead style="text-align: center; position: sticky; top:0; background-color: white;">
            <tr>
              <th>Number #</th>
              <th data-sort="customer" class="sortable">Customer</th>
              <th data-sort="name" class="sortable">Device Name</th>
            </tr>
          </thead>
          <tbody id="list-fw">
            {% for device in list_of_deeds %}
            <tr>
              <td>{{ forloop.counter }}</td>
              <td>{{ device.customer }}</td>
              <td>
                <a href="/detail/{{ device.id }}" target="_blank">{{ device.name }}</a>
              </td>
            </tr>
            {% endfor %}
          </tbody>
          <tbody id="list-results-fw" class="not-visible"></tbody>
        </table>
      </div>
    </div>
  </div>
</div>

I have the search working, to display the records live for what i am looking for, and the sorting works on the initial load, but if i search for something and the results come up the sorting won’t work on those results, i can’t figure out why. Can someone please help me out with this?

onLoad does not work when replacing with html-react-parser

I am using the html-react-parser library to convert a string representing an HTML snippet into a React component. The string contains a component and a with an onload attribute. Here’s an example of the HTML string:

const html = `
  <div id="component">...</div>
  <script src="/component/index.js" onload="initComponent(94239483, 4)"></script>
`;

The HTML string is processed and converted into a React component using html-react-parser. The approach involves parsing the string and replacing local sources with sources hosted on a CDN. To achieve this, I use the replace option from html-react-parser. Here is my current implementation:

import parse from 'html-react-parser';

const html = `
  <div id="component">...</div>
  <script src="/component/index.js" onload="initComponent(94239483, 4)"></script>
`;

const parsedHTML = parse(html, {
  replace(domNode) {
    if (isAReplaceableScript(domNode, 'true')) {
      return replaceLocalScript(domNode, customization.javascript);
    }
  },
});
const replaceLocalScript = (domNode, files) => {
  const localSource = domNode.attribs.src;
  const cdnSource = files[localSource];
  const { attribs } = domNode;
  const onLoad = new Function('alert("It is working")');
  const updatedAttribs = { ...attribs, src: cdnSource };
  return cdnSource ? <script {...updatedAttribs} onLoad={onLoad} defer /> : <></>;
};

The updated appears correctly in the browser’s HTML with the src attribute pointing to the CDN URL, but the onLoad event does not trigger. When inspecting the script in the browser, the onLoad property does not appear.

Questions

  1. What might be missing for the onLoad event to trigger?
  2. Is it possible that React or html-react-parser is ignoring the onLoad event for <script> tags?
  3. Should I use a different approach to dynamically load scripts?

Additional Context

  • Due to technical limitations, this approach is the most cost-effective to implement.
  • The HTML string is processed to be converted into a React component, as this project is built with React.

JsBarcode is not a function, Uncaught (in promise) Object, require is not defined, ZXing is not defined

I can’t get this javascript code to work right, it keeps giving me errors.

This is my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Barcode Generator and Scanner</title>
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode"></script>
    <script src="https://unpkg.com/@zxing/browser@latest"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        .container {
            margin-bottom: 20px;
        }
        video {
            width: 100%;
            max-width: 400px;
        }
        svg {
            margin: 20px 0;
        }
    </style>
</head>
<body>
    <h1>Barcode Generator and Scanner</h1>
    
    <!-- Barcode Generator -->
    <div class="container">
        <h2>Generate Barcode</h2>
        <label for="rewardsLevel">Rewards Level:</label>
        <select id="rewardsLevel">
            <option value="1">Silver</option>
            <option value="2">Gold</option>
            <option value="3">Platinum</option>
        </select><br>
        <label for="email">Email:</label>
        <input type="email" id="email" placeholder="[email protected]"><br>
        <label for="issueDate">Issue Date:</label>
        <input type="date" id="issueDate"><br>
        <label for="name">Name:</label>
        <input type="text" id="name" placeholder="Your Name"><br><br>
        <button onclick="generateBarcode()">Generate Barcode</button>
        <svg id="barcode"></svg>
        <button id="downloadBarcode" onclick="downloadSVG()" style="display:none;">Download Barcode</button>
    </div>

    <!-- Barcode Scanner -->
    <div class="container">
        <h2>Scan Barcode</h2>
        <button onclick="startScanner()">Start Scanner</button>
        <button onclick="resetScanner()">Reset Scanner</button>
        <video id="video" autoplay muted playsinline></video>
        <div id="decodedOutput" style="margin-top: 20px;"></div>
    </div>

    <script>
        // Barcode Generator
        function generateBarcode() {
            const rewardsLevel = document.getElementById("rewardsLevel").value;
            const email = document.getElementById("email").value;
            const issueDate = document.getElementById("issueDate").value.replace(/-/g, '');
            const name = document.getElementById("name").value;

            if (!email || !issueDate || !name) {
                alert("Please fill in all fields.");
                return;
            }

            const barcodeValue = `${rewardsLevel}*${issueDate}*${email}*${name}`;
            const barcodeElement = document.getElementById("barcode");

            JsBarcode(barcodeElement, barcodeValue, {
                format: "CODE128",
                width: 2,
                height: 100,
                displayValue: true
            });

            document.getElementById("downloadBarcode").style.display = "block";
        }

        // Download Barcode
        function downloadSVG() {
            const svg = document.getElementById("barcode");
            const serializer = new XMLSerializer();
            const source = serializer.serializeToString(svg);
            const blob = new Blob([source], { type: "image/svg+xml;charset=utf-8" });
            const url = URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.href = url;
            link.download = "barcode.svg";
            link.click();
            URL.revokeObjectURL(url);
        }

        // Barcode Scanner
        let codeReader;
        const videoElement = document.getElementById("video");

        async function startScanner() {
            if (!codeReader) {
                codeReader = new ZXing.BrowserMultiFormatReader();
            }
            const devices = await codeReader.listVideoInputDevices();
            if (devices.length === 0) {
                alert("No video input devices found.");
                return;
            }

            const selectedDeviceId = devices[0].deviceId;
            codeReader.decodeFromVideoDevice(selectedDeviceId, videoElement, (result, error) => {
                if (result) {
                    displayDecodedData(result.text);
                    codeReader.reset(); // Stop scanning once a code is detected
                }
                if (error) {
                    console.error(error);
                }
            });
        }

        function displayDecodedData(data) {
            const [level, date, email, name] = data.split('*');
            const levels = { "1": "Silver", "2": "Gold", "3": "Platinum" };
            const formattedDate = new Date(date.substring(0, 4), date.substring(4, 6) - 1, date.substring(6, 8))
                .toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" });

            const outputDiv = document.getElementById("decodedOutput");
            outputDiv.innerHTML = `
                <p><strong>Rewards Level:</strong> ${levels[level]}</p>
                <p><strong>Issue Date:</strong> ${formattedDate}</p>
                <p><strong>Email:</strong> ${email}</p>
                <p><strong>Name:</strong> ${name}</p>
            `;
        }

        function resetScanner() {
            if (codeReader) {
                codeReader.reset();
            }
            videoElement.srcObject = null;
            document.getElementById("decodedOutput").innerHTML = "";
        }
    </script>
</body>
</html>

And i get these errors when i run it:

Uncaught ReferenceError: require is not defined
JsBarcode.js:3:17

Uncaught (in promise) Object
card:1

Uncaught (in promise) Object
browser-polyfill.min.js:1

Uncaught (in promise) Object
iframefallback:1

Uncaught (in promise) Object
card:1

Uncaught (in promise) Object
browser-polyfill.min.js:1

Uncaught TypeError: JsBarcode is not a function
card:526

TypeError: JsBarcode is not a function
web.assets_frontend_lazy.min.js:4107

ReferenceError: ZXing is not defined
card:556

Audio Context in iOS won’t resume from suspend

I have a website that plays audio. It is most often run inside of a WebView in an iOS app, though it can be accessed directly. The audio is being played using an AudioContext. When the device goes to sleep, or the screen is put to sleep, the AudioContext will be suspended. I am listening to the statechange event and if the audio state changes to suspended or interrupted I will display a pause indicator when the user comes back to the app. Clicking the pause indicator triggers the following code:

async function resumeAudio() {
    if (context.state === SUSPENDED || context.state === INTERRUPTED) {
        try {
            console.log(`Audio context state is ${context.state}. Attempting to resume audio context.`);
            await context.resume();
            console.log(`Audio context resumed. State is now ${context.state}.`);
        } catch (e) {
            console.error('Error resuming audio context: ', e);
        }
    }
}

Sometimes when the context is suspended the resume call will work, sometimes it won’t. When it fails to work the await context.resume() call never resolves.

Is there any explanation for why it gets stuck in suspend? The only reasons I’ve seem so far deal with needing the context.resume() call to be part of a user input, which is how I am doing it.


Edit: Realized just after posting that I forgot to await the context.resume(). I edited the function to be async and am now awaiting the resume.

Why userscript cannot intercept all requests?

Similar to this question. The following userscript intercepts fetch and XMLHttpRequest requests and log their url’s to the console. But, why it doesn’t intercept all requests? for example it doesn’t log: https://www.youtube.com/s/desktop/508deff1/img/logos/favicon.ico and https://tpc.googlesyndication.com/sodar/56-y-0RG.js

// ==UserScript==
// @name         YouTube Urls
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  URLs on YouTube.
// @author       me
// @match        https://www.youtube.com/*
// @grant        none
// @run-at       document-start
// ==/UserScript==

(function() {
    'use strict';

    // intercept fetch requests
    const originalFetch = window.fetch;

    window.fetch = function(url, options) {

        console.log(url)
        return originalFetch(url, options);
    };


    // intercept XMLHttpRequest
    const originalXhrOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function(method, url, async, user, password) {

        console.log(url)
        return originalXhrOpen.apply(this, arguments);
    };

})();

Both resources aren’t preloaded:enter image description here

Unobserved Error at end of App Script Code

I’m encountering a “SyntaxError: Unexpected end of input” on line 1646 in Code.gs. This occurs at the end of my code, where the final function is:

function getSpreadsheet() {
    return SheetUtils.getSpreadsheet();
}

There’s no visible code after this function. As a first-time coder, I’d appreciate help understanding and resolving this error. Thank you.

I reviewed the two prior functions, and they appear to have the proper closing Brackets.

Why is the browser not including the full URL parameter

When the request is made to the aws endpoint, why is it cutting off some of the url paramerter ?text=?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search Engine</title>
    <style>
        /* CSS styles remain the same */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f9;
        }

        .container {
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        h1 {
            text-align: center;
            color: #333;
        }

        .search-bar {
            display: flex;
            justify-content: space-between;
        }

        .search-bar input[type="text"] {
            width: 80%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }

        .search-bar button {
            padding: 10px 15px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }

        .search-bar button:hover {
            background: #0056b3;
        }

        .results {
            margin-top: 20px;
        }

        .result {
            margin-bottom: 15px;
            padding: 10px;
            background: #f9f9f9;
            border-radius: 4px;
            border: 1px solid #ddd;
        }

        .result h3 {
            margin: 0 0 10px;
            cursor: pointer;
            color: #007bff;
        }

        .result h3:hover {
            text-decoration: underline;
        }

        .result p {
            margin: 0;
            padding: 0;
        }

        .question {
            cursor: pointer;
            margin: 10px 0;
        }

        .question span {
            margin-right: 5px;
            font-size: 18px;
            color: #555;
        }

        .question:hover {
            color: #007bff;
        }

        .answer {
            display: none;
            margin-left: 20px;
            color: #333;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Search Engine</h1>
        <div class="search-bar">
            <input type="text" id="query" placeholder="Enter your query">
            <button onclick="performSearch()">Search</button>
        </div>
        <div class="results" id="results"></div>
    </div>

    <script>
        const apiInstructions = "You are an AI Generated section of a search engine. If you feel the AI Generated section would be useful, enter a response in this format: "(One to Six word answer); (one-two sentence description followed by a semi-colon); (follow up question the user may ask #1); (response to question #1); (follow up question the user may ask #2); (response to question #2); (follow up question the user may ask #3); (response to question #3)". The questions are expandable to display the answers, so make sure to include the semicolons between questions and answers. This is fully automated. Your answer should not include any new lines, or markup. It should only include semicolons, periods, and text. Be sure to include the semicolons between the answer, description, question 1, answer 1, question 2, answer 2, question 3, and answer 3. If you think the AI Generated content section would not be helpful, enter: "DO NOT DISPLAY" to hide the AI Generated content section. If it seems to be cut off, use "DO NOT DISPLAY". If the answer to a question is "no", you should still display an answer. The user has searched for "";


        async function performSearch() {
            const query = document.getElementById('query').value;
            const encodedQuery = encodeURIComponent(query);
            const url = `https://yw85opafq6.execute-api.us-east-1.amazonaws.com/default/boss_mode_15aug?text=${apiInstructions}${encodedQuery}"`;

            try {
                const response = await fetch(url);
                const text = await response.text();

                if (text === "DO NOT DISPLAY") {
                    document.getElementById('results').innerHTML = "<p>No results found.</p>";
                } else {
                    const data = text.split(';');
                    const title = data[0];
                    const description = data[1];
                    const questions = [
                        { question: data[2], answer: data[3] },
                        { question: data[4], answer: data[5] },
                        { question: data[6], answer: data[7] },
                    ];

                    displayResults(title, description, questions);
                }
            } catch (error) {
                document.getElementById('results').innerHTML = "<p>Error fetching results.</p>";
                console.error("Error:", error);
            }
        }

        // ... (displayResults and toggleAnswer functions remain the same)

        function displayResults(title, description, questions) {
            const resultsContainer = document.getElementById('results');
            resultsContainer.innerHTML = `
                <div class="result">
                    <h3>${title}</h3>
                    <p>${description}</p>
                    ${questions
                        .map(
                            (q, index) =>
                                `<div class="question" onclick="toggleAnswer(${index})">
                                    <span>▸</span> ${q.question}
                                 </div>
                                 <div class="answer" id="answer-${index}">${q.answer}</div>`
                        )
                        .join('')}
                </div>
            `;
        }

        function toggleAnswer(index) {
            const answer = document.getElementById(`answer-${index}`);
            const question = answer.previousElementSibling;
            if (answer.style.display === "block") {
                answer.style.display = "none";
                question.querySelector('span').innerHTML = "▸";
            } else {
                answer.style.display = "block";
                question.querySelector('span').innerHTML = "▾";
            }
        }
    </script>
</body>
</html>

JavaScript how to remove hard coded values on ‘click’ function

Hello world would be grateful for any help i have some redundancy code issues, everything works fine but i had to repeat the same code about 100 times for my unique identifier.
I have a add button that gets assigned a unique identifier for the example below my add button id is addbtn3 so this finds the JavaScript with addbtn3 and does stuff.
I would really like when the addbtn3 is clicked the JavaScript is generic like:

$("body").on("click", "#addbtn + row", function () { 

and it knows that the row value is three so i don’t have it hard coded.
any help would be appreciated

 $("body").on("click", "#addbtn3", function () {

  var toolListUpdate = $("#ToolList3");
  var genericDropDownListUpdateOne = $("#GenericDropdownOne3");
  var genericDropDownListUpdateTwo = $("#GenericDropdownTwo3");
  var genericDropDownListUpdateThree = $("#GenericDropdownThree3");
  var genericDropDownListUpdateFour = $("#GenericDropdownFour3");
  var changeNoticeNumberLinkUpdate = $("#changeNoticeNumberLink3");
  var holdLotNumberLinkUpdate = $("#holdLotNumberLink3");
  var hotLotNumberLinkUpdate = $("#hotLotNumberLink3");
  var wITALinkUpdate = $("#wITANumberLink3");
  var commentUpdateSmall = $("#commentSmall3");
  var commentUpdateMedium = $("#commentMedium3");
  var commentUpdateLarge = $("#commentLarge3");
  var fieldid = $("#fieldid3");

  var tBody = $("#tblUpdate3 > #tbodyUpdate3")[0];

  var row = tBody.insertRow(-1);

  var cell = $(row.insertCell(-1));
  cell.html(fieldid.val());

  var cell = $(row.insertCell(-1));
  cell.html(toolListUpdate.val());

  cell = $(row.insertCell(-1));
  cell.html(genericDropDownListUpdateOne.val());

  cell = $(row.insertCell(-1));
  cell.html(genericDropDownListUpdateTwo.val());

  cell = $(row.insertCell(-1));
  cell.html(genericDropDownListUpdateThree.val());

  cell = $(row.insertCell(-1));
  cell.html(genericDropDownListUpdateFour.val());

  cell = $(row.insertCell(-1));
  cell.html(changeNoticeNumberLinkUpdate.val());

  cell = $(row.insertCell(-1));
  cell.html(holdLotNumberLinkUpdate.val());

  cell = $(row.insertCell(-1));
  cell.html(hotLotNumberLinkUpdate.val());

  cell = $(row.insertCell(-1));
  cell.html(wITALinkUpdate.val());

  cell = $(row.insertCell(-1));
  cell.html(commentUpdateSmall.val());

  cell = $(row.insertCell(-1));
  cell.html(commentUpdateMedium.val());

  cell = $(row.insertCell(-1));
  cell.html(commentUpdateLarge.val());

  cell = $(row.insertCell(-1));
  var timestamp = $("<div>@DateTime.Now</div>");
  cell.append(timestamp);

  cell = $(row.insertCell(-1));
  var btnRemove = $("<input />");
  btnRemove.attr("type", "button");
  btnRemove.attr("class", "btn btn-link remove")
  btnRemove.attr("id", "remove")
  btnRemove.attr("style", "font-size: 11px; color:red;")
  btnRemove.val("- Remove");
  cell.append(btnRemove);

  var tBodyUpdate = $("#tblUpdate > #tbodyUpdate")[0];

  var row = tBodyUpdate.insertRow(-1);

  var cell = $(row.insertCell(-1));
  cell.html(fieldid.val());

  var cell = $(row.insertCell(-1));
  cell.html(toolListUpdate.val());

  cell = $(row.insertCell(-1));
  cell.html(genericDropDownListUpdateOne.val());

  cell = $(row.insertCell(-1));
  cell.html(genericDropDownListUpdateTwo.val());

  cell = $(row.insertCell(-1));
  cell.html(genericDropDownListUpdateThree.val());

  cell = $(row.insertCell(-1));
  cell.html(genericDropDownListUpdateFour.val());

  cell = $(row.insertCell(-1));
  cell.html(changeNoticeNumberLinkUpdate.val());

  cell = $(row.insertCell(-1));
  cell.html(holdLotNumberLinkUpdate.val());

  cell = $(row.insertCell(-1));
  cell.html(hotLotNumberLinkUpdate.val());

  cell = $(row.insertCell(-1));
  cell.html(wITALinkUpdate.val());

  cell = $(row.insertCell(-1));
  cell.html(commentUpdateSmall.val());

  cell = $(row.insertCell(-1));
  cell.html(commentUpdateMedium.val());

  cell = $(row.insertCell(-1));
  cell.html(commentUpdateLarge.val());

  cell = $(row.insertCell(-1));
  var timestamp = $("<div>@DateTime.Now</div>");
  cell.append(timestamp);


  toolListUpdate.val("");
  genericDropDownListUpdateOne.val("");
  genericDropDownListUpdateTwo.val("");
  genericDropDownListUpdateThree.val("");
  genericDropDownListUpdateFour.val("");
  changeNoticeNumberLinkUpdate.val("");
  holdLotNumberLinkUpdate.val("");
  hotLotNumberLinkUpdate.val("");
  wITALinkUpdate.val("");
  commentUpdateSmall.val("");
  commentUpdateMedium.val("");
  commentUpdateLarge.val("")

});

How to gracefully handle missing user data in React without revealing backend issues?

I’m building a microservices-based application and in the front-end I’m using React and TypeScript. In one of the services, I fetch post data to display to users. Each post has a user field containing details about the user who created the post. However, if the user service is down, the user field in the response is null.

Here’s an example of the response when the user service is unavailable:

{
  "id": 1,
  "content": "Sample post content",
  "user": null
}

In such cases, I want to display the post without revealing to the user that there’s an issue (like the user service being down). For example, I might display something like “Anonymous” in place of the user’s name. However, I want to avoid explicitly using if-else or ternary operations to handle the null value.

I’ve Tried Using optional chaining, but it still requires me to provide fallback logic like user?.name || “Anonymous” also I’ve Tried Wrapping the logic in a function, but it feels repetitive across components.

What’s the best way to cleanly handle such scenarios in React, ensuring maintainability and avoiding repetitive conditional logic throughout the codebase?

How can I pass custom data into an Incisor callback function with a button click?

I’m learning Incisor and I’m trying to understand how to pass custom data into my callback function when a button is clicked. I have a block of JSON data and a button. I am using a pressCallback and passing my data as a parameter. However, when I log the callback argument, I’m seeing a MouseEvent object instead of the data I passed in.

Here is my sample code:

class ProjectMain {

    init() {
        
        let data = {"id": 0, "email": "[email protected]", "active": true};

        this.button = new Button( nc.graphicAssets.WhiteBox, nc.mainScene, "MyButton" );
        this.button.addPressCallback( this, "myPressCallback", data );

        this.myPressCallback = function( data ) {
            console.log('callback:', data );
        }
    }
}

In this code, when I click the button, the callback function is triggered, but the console logs a MouseEvent object rather than the data object I passed in. How can I properly pass and access the custom data in the callback function?

Having An issue about calling Gemini Api in Electron Js

I am having an issue with gemini api in electron js in this code I’m trying to make chatbot which remembers the previous messages unfortunately I’m getting an Error Message:

Uncaught Error: Check dependency list! Synchronous require cannot resolve module ‘@google/generative-ai’. This is the first mention of this module!



let history=[

]


const sendbtn=document.getElementById("send");

sendbtn.addEventListener("click", ()=>{
  const messageDiv = document.createElement("div");
  messageDiv.classList.add("outgoing");
  messageDiv.innerText = prompttext.value;
  messagesContainer.appendChild(messageDiv);
  history.push({role: "user", content: prompttext.value})
  prompttext.value=""
  run()
})

const prompttext=document.getElementById("prompt");
const messagesContainer=document.getElementById("chat-main")

const { GoogleGenerativeAI } = require("@google/generative-ai");
const genAI = new GoogleGenerativeAI("myApıKey");

async function run() {
  // The Gemini 1.5 models are versatile and work with multi-turn conversations (like chat)
  const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash"});

  const chat = model.startChat({
    history,
    generationConfig: {
      maxOutputTokens: 100,
    },
  });

  const result = await chat.sendMessage(prompttext.textContent);
  const response = await result.response;
  const text = response.text();
  history.push({role: "model", content:text})
  const messageDiv = document.createElement("div");
  messageDiv.classList.add("incoming");
  messageDiv.innerText = text;
  messagesContainer.appendChild(messageDiv);
}