React useState instantly calling the function I store in it as variable on re-render?

I am trying to make a filehandling system where you can delete the documents from the list of documents with the Delete button next to them. Upon clicking it, the usual pop-up window appears, asking for confirmation, and once clicking the Delete button there too, the file should be deleted. Problem is, that’s not what’s happening. The file is getting deleted right when the first Delete button is getting clicked. It would seem the useState in the App.js to which I pass the method that does the deleting calls it instantly on the re-render for some reason?

In the DocumentList.js:

    const deleteSetter = () => {
    
        const deleteFile = () => {
    
            handleClick(path, fileName)
        }
    
        deleteButtonSetter(deleteFile)
        deleteFileSetter(fileName)
        deleteWindowSetter(true)
    }

    return (

        ...

        <div className="document-buttons">

            ...

            <ButtonWithIcon
                index={1}
                imageComponent={<DeleteIcon/>}
                onClickFunction={deleteSetter}
            />

        </div>
    )

In the App.js:

    const [isDelete, setDelete] = useState(false)
    const [deleteFile, setDeleteFile] = useState(null)
    const [deleteButton, setDeleteButton] = useState(null)

    return (
    
        <div className="App">
    
          ...
    
          {isDelete ?
            (
              <DialogueWindow
    
                elements={
    
                  <FileDeleter
                    fileName={deleteFile}
                    deleteButtonSetter={deleteButton}
                    closeButtonSetter={setDelete}
                  />
                }
              />
            ) :
            null
          }
    
        </div>
     )

In the FileDeleter.js:

return (

    <div className="button-container">

                <DialogueButton
                    text="Delete"
                    isAvailable={fileName ? true : false}
                    onClickFunction={() => {
                        
                        deleteButtonSetter()
                    }}
                />

                ...

    </div>
)

What could be the issue? At no point do I use () after the name of the function, except when I finally call it in the FileDeleter’s onClick event. So why does it get called right at the useState update?

Set Start Date to Ajax Calendar Extender Control via Javascript

I have two textboxes on a webform (asp.net/c#) with each having the ajax calendar extender so when a user clicks in the textbox a calendar appears. The first one is date from while the second one is a date to. I want to be able to set the start date of the calendar extender of the date to, to be of the date selected in the date from.

I know this can be done by autopostbacking the textchange on the date from textbox then we can get the date from the textbox and apply to the To calendar extender, however I would prefer if there was a way we could do this without going back to the server. I am thinking javascript, we can find again look at the textchange of the textbox, like this

<asp:TextBox ID="txtFromDate" runat="server" onchange="javascript:SetToDate();"></asp:TextBox>

with the other textbox as

<asp:TextBox ID="txtToDate" runat="server"></asp:TextBox>
<act:CalendarExtender ID="calToDate" runat="server" PopupButtonID="imgPopUp" TargetControlID="txtToDate" Format="dd/MM/yyyy">
</act:CalendarExtender>

I was thinking I could have something like this in javascript

function SetToDate() {

    var datestart = new Date(document.getElementById('<%=txtFromDate.ClientID %>').value);
    document.getElementById('<%=calToDate.ClientID %>').StartDate = datestart;

}

However as you can see .StartDate does not belong like this, so how else can I apply the start date to calToDate via javascript.

Any help will be appreciated

Prisma model undefined even after npx prisma generate – timeSettings.findFirst is not a function

I’m working with a Next.js 15 app using Prisma with PostgreSQL. I recently added a new model TimeSettings to my schema.prisma, like so:

model TimeSettings {
id              String   @id @default(uuid())
minAdvanceHours Int      @default(2)
createdAt       DateTime @default(now())
updatedAt       DateTime @updatedAt    }

After that, I ran the following commands:

npx prisma generate
npx prisma db push

No errors during these commands. But when I try to use the model in my route like this:

const settings = await prisma.timeSettings.findFirst();

I get this runtime error:

TypeError: Cannot read properties of undefined (reading 'findFirst')

generator client {
  provider = "prisma-client-js"
  output   = "../generated"
}

datasource db {
  provider = "postgresql"
  url      = "postgresql://username:neondbstring?sslmode=require"
}

model User {
  id            String   @id @default(uuid())
  name          String
  email         String   @unique
  phone         String   @unique
  role          String
  photo         Json?
  createdAt     DateTime @default(now())
  updatedAt     DateTime @updatedAt
  isVerifiedOtp Boolean?
  driver        Driver?
}

model Driver {
  id                String    @id @default(uuid())
  userId            String    @unique
  email             String    @unique
  association       String
  licenseExpiry     String
  carType           String
  ac                Boolean
  carLicensePlate   String
  licenseFile       Json
  taxiBadge         Json
  carInsurance      Json
  operatorLicense   Json?
  carPhotos         Json[]
  applicationStatus String    @default("pending")
  statusUpdatedAt   DateTime  @default(now())
  trackingId        String    @unique
  totalEarnings     Float     @default(0)
  totalRides        Int       @default(0)
  adminNotes        String?
  available         Boolean?
  resubmissionLink  String?
  isOtpVerified     Boolean   @default(false)
  acceptedBookings  Booking[]
  user              User      @relation(fields: [userId], references: [id], onDelete: Cascade)
  offers            Offer[]
}

model Booking {
  id                String    @id @default(uuid())
  bookingId         String    @unique
  pickupCoords      Float[]
  destCoords        Float[]
  viaCoords         Json?
  pickupPoint       String
  destination       String
  via               String?
  customerName      String
  customerEmail     String
  customerPhone     String
  estimatedDistance Float
  estimatedFare     Float
  cartype           String
  pickupDate        String
  pickupTime        String
  status            String    @default("pending")
  pickup_status     String?
  driverNote        String?
  drivertoken       String?
  driverId          String?
  completedAt       DateTime?
  createdAt         DateTime  @default(now())
  updatedAt         DateTime  @updatedAt
  acceptedBy        Driver?   @relation(fields: [driverId], references: [id])
  offers            Offer[]
}

model Offer {
  id        String   @id @default(uuid())
  bookingId String
  driverId  String
  fare      Float
  status    String   @default("pending")
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  booking   Booking  @relation(fields: [bookingId], references: [id], onDelete: Cascade)
  driver    Driver   @relation(fields: [driverId], references: [id], onDelete: Cascade)
}

model Admin {
  id            String  @id @default(uuid())
  email         String  @unique
  isOtpVerified Boolean @default(false)
}

model Otp {
  id        String   @id @default(uuid())
  email     String
  otp       String
  phone     String?
  createdAt DateTime @default(now())
  expiresAt DateTime
}

model Notification {
  id        String   @id @default(uuid())
  title     String
  message   String
  type      String
  recipient String
  data      Json
  read      Boolean  @default(false)
  createdAt DateTime @default(now())
}

model TimeSettings {
  id              String   @id @default(uuid())
  minAdvanceHours Int      @default(2)
  createdAt       DateTime @default(now())
  updatedAt       DateTime @updatedAt
}

lib/Prisma.ts

import { PrismaClient } from '@prisma/client'; // adjust path if needed

const globalForPrisma = globalThis;

const prisma = globalForPrisma.prisma ?? new PrismaClient();

if (!globalForPrisma.prisma) {
  globalForPrisma.prisma = prisma;
}

export default prisma;

lib/db.js

import { PrismaClient } from '@prisma/client';

const globalForPrisma = globalThis;

// Reuse existing PrismaClient in development
const prisma = globalForPrisma.prisma ?? new PrismaClient();

if (process.env.NODE_ENV !== 'production') {
  globalForPrisma.prisma = prisma;
}

export const connectDB = async () => {
  try {
    await prisma.$connect();
    console.log('✅ Database connected successfully');
    return prisma;
  } catch (error) {
    console.error('❌ Error connecting to database:', error);
    process.exit(1);
  }
};

export { prisma };
export default prisma;

time-settings route

import prisma from '@/lib/db';
import { NextResponse } from 'next/server';
import { connectDB } from '@/lib/db';

console.log(prisma); // In dev only — to inspect available models

// GET: fetch or initialize settings
export async function GET() {
  try {
     await connectDB()
    let settings = await prisma.timesettings.findFirst();

    if (!settings) {
      settings = await prisma.timesettings.create({
        data: {
          minAdvanceHours: 4,
        },
      });
    }

    return NextResponse.json({
      success: true,
      settings,
    });
  } catch (error) {
    console.error('Error fetching time settings:', error);
    return NextResponse.json(
      {
        success: false,
        message: `Failed to fetch time settings,${error}`,
      },
      { status: 500 }
    );
  }
}

// POST: update or create settings
export async function POST(request) {
  try {
     await connectDB()
    const data = await request.json();
    const { minAdvanceHours } = data;

    const existing = await prisma.timesettings.findFirst();

    let settings;
    if (existing) {
      settings = await prisma.timesettings.update({
        where: { id: existing.id },
        data: {
          minAdvanceHours,
        },
      });
    } else {
      settings = await prisma.timesettings.create({
        data: {
          minAdvanceHours,
        },
      });
    }

    return NextResponse.json({
      success: true,
      settings,
    });
  } catch (error) {
    console.error('Error updating time settings:', error);
    return NextResponse.json(
      {
        success: false,
        message: `Failed to update time settings, ${error}`,
      },
      { status: 500 }
    );
  }
}

// DELETE: remove all settings
export async function DELETE() {
  try {
     await connectDB()
    await prisma.timesettings.deleteMany();

    return NextResponse.json({
      message: 'Bro! Destruction is done',
      success: true,
    });
  } catch (error) {
    console.error('Error deleting time settings:', error);
    return NextResponse.json(
      {
        success: false,
        message: 'Failed to delete time settings',
      },
      { status: 500 }
    );
  }
}

Finally, Console.log Prisma response

 _clientVersion: '6.7.0',
      _errorFormat: 'colorless',
      _tracingHelper: Io {},
      _middlewares: [Jn],
      _previewFeatures: [],
      _activeProvider: 'postgresql',
      _globalOmit: undefined,
      _extensions: [e],
      _engine: [Qr],
      _appliedParent: [Object],
      _createPrismaPromise: [Function (anonymous)],
      '$metrics': [Fr],
      '$extends': [Function: Ka],
      constructor: [class r],
      '$use': [Function: $use],
      '$on': [Function: $on],
      '$connect': [Function: $connect],
      '$disconnect': [AsyncFunction: $disconnect],
      '$executeRawInternal': [Function: $executeRawInternal],
      '$executeRaw': [Function: $executeRaw],
      '$executeRawUnsafe': [Function: $executeRawUnsafe],
      '$runCommandRaw': [Function: $runCommandRaw],
      '$queryRawInternal': [AsyncFunction: $queryRawInternal],
      '$queryRaw': [Function: $queryRaw],
      '$queryRawTyped': [Function: $queryRawTyped],
      '$queryRawUnsafe': [Function: $queryRawUnsafe],
      _transactionWithArray: [Function: _transactionWithArray],
      _transactionWithCallback: [AsyncFunction: _transactionWithCallback],
      _createItxClient: [Function: _createItxClient],
      '$transaction': [Function: $transaction],
      _request: [Function: _request],
      _executeRequest: [AsyncFunction: _executeRequest],
      _hasPreviewFlag: [Function: _hasPreviewFlag],
      '$applyPendingMigrations': [Function: $applyPendingMigrations],
      user: [Object],
      driver: [Object],
      booking: [Object],
      offer: [Object],
      admin: [Object],
      otp: [Object],
      notification: [Object],
      '$parent': [Object],
      [Symbol()]: [Object]
    },
    [Symbol()]: {
      _originalClient: [Object],
      _runtimeDataModel: [Object],
      _requestHandler: [zn [RequestHandler]],
      _connectionPromise: undefined,
      _disconnectionPromise: undefined,
      _engineConfig: [Object],
      _accelerateEngineConfig: [Object],
      _clientVersion: '6.7.0',
      _errorFormat: 'colorless',
      _tracingHelper: Io {},
      _middlewares: [Jn],
      _previewFeatures: [],
      _activeProvider: 'postgresql',
      _globalOmit: undefined,
      _extensions: [e],
      _engine: [Qr],
      _appliedParent: [Object],
      _createPrismaPromise: [Function (anonymous)],
      '$metrics': [Fr],
      '$extends': [Function: Ka]
    }
  },
  [Symbol()]: {
    _originalClient: {
      _originalClient: [Object],
      _runtimeDataModel: [Object],
      _requestHandler: [zn [RequestHandler]],
      _connectionPromise: undefined,
      _disconnectionPromise: undefined,
      _engineConfig: [Object],
      _accelerateEngineConfig: [Object],
      _clientVersion: '6.7.0',
      _errorFormat: 'colorless',
      _tracingHelper: Io {},
      _middlewares: [Jn],
      _previewFeatures: [],
      _activeProvider: 'postgresql',
      _globalOmit: undefined,
      _extensions: [e],
      _engine: [Qr],
      _appliedParent: [Object],
      _createPrismaPromise: [Function (anonymous)],
      '$metrics': [Fr],
      '$extends': [Function: Ka]
    },
    _runtimeDataModel: { models: [Object], enums: {}, types: {} },
    _requestHandler: <ref *1> zn [RequestHandler] {
      client: [Object],
      dataloader: [Kn [DataLoader]],
      logEmitter: [EventEmitter]
    },
    _connectionPromise: undefined,
    _disconnectionPromise: undefined,
    _engineConfig: {
      cwd: 'D:\Prod_Ready\englishtaxis-nextjs-prisma\prisma',
      dirname: 'D:\Prod_Ready\englishtaxis-nextjs-prisma\node_modules\.prisma\client',
      enableDebugLogs: false,
      allowTriggerPanic: undefined,
      prismaPath: 'D:\Prod_Ready\englishtaxis-nextjs-prisma\node_modules\.prisma\client\query_engine-windows.dll.node',
      engineEndpoint: undefined,
      generator: [Object],
      showColors: false,
      logLevel: undefined,
      logQueries: undefined,
      env: [Object],
      flags: [],
      engineWasm: undefined,
      compilerWasm: undefined,
      clientVersion: '6.7.0',
      engineVersion: '3cff47a7f5d65c3ea74883f1d736e41d68ce91ed',
      previewFeatures: [],
      activeProvider: 'postgresql',
      inlineSchema: '// This is your Prisma schema file,n' +
        '// learn more about it in the docs: https://pris.ly/d/prisma-scheman' +
        'n' +
        '// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?n' +
        '// Try Prisma Accelerate: https://pris.ly/cli/accelerate-initn' +
        'n' +
        'generator client {n' +
        '  provider = "prisma-client-js"n' +
        '}n' +
        'n' +
        'datasource db {n' +
        '  provider = "postgresql"n' +
        '  url      = "xxxxxxxxxx"n' +
        '}n' +
        'n' +
        'model User {n' +
        '  id            String   @id @default(uuid())n' +
        '  name          Stringn' +
        '  email         String   @uniquen' +
        '  phone         String   @uniquen' +
        '  role          Stringn' +
        '  photo         Json?n' +
        '  createdAt     DateTime @default(now())n' +
        '  updatedAt     DateTime @updatedAtn' +
        '  isVerifiedOtp Boolean?n' +
        '  driver        Driver?n' +
        '}n' +
        'n' +
        'model Driver {n' +
        '  id                String    @id @default(uuid())n' +
        '  userId            String    @uniquen' +
        '  email             String    @uniquen' +
        '  association       Stringn' +
        '  licenseExpiry     Stringn' +
        '  carType           Stringn' +
        '  ac                Booleann' +
        '  carLicensePlate   Stringn' +
        '  licenseFile       Jsonn' +
        '  taxiBadge         Jsonn' +
        '  carInsurance      Jsonn' +
        '  operatorLicense   Json?n' +
        '  carPhotos         Json[]n' +
        '  applicationStatus String    @default("pending")n' +
        '  statusUpdatedAt   DateTime  @default(now())n' +
        '  trackingId        String    @uniquen' +
        '  totalEarnings     Float     @default(0)n' +
        '  totalRides        Int       @default(0)n' +
        '  adminNotes        String?n' +
        '  available         Boolean?n' +
        '  resubmissionLink  String?n' +
        '  acceptedBookings  Booking[]n' +
        '  user              User      @relation(fields: [userId], references: [id], onDelete: Cascade)n' +
        '  offers            Offer[]n' +
        '  isOtpVerified     Boolean   @default(false)n' +
        '}n' +
        'n' +
        'model Booking {n' +
        '  id                String    @id @default(uuid())n' +
        '  bookingId         String    @uniquen' +
        '  pickupCoords      Float[]n' +
        '  destCoords        Float[]n' +
        '  viaCoords         Json?n' +
        '  pickupPoint       Stringn' +
        '  destination       Stringn' +
        '  via               String?n' +
        '  customerName      Stringn' +
        '  customerEmail     Stringn' +
        '  customerPhone     Stringn' +
        '  estimatedDistance Floatn' +
        '  estimatedFare     Floatn' +
        '  cartype           Stringn' +
        '  pickupDate        Stringn' +
        '  pickupTime        Stringn' +
        '  status            String    @default("pending")n' +
        '  pickup_status     String?n' +
        '  driverNote        String?n' +
        '  drivertoken       String?n' +
        '  driverId          String?n' +
        '  completedAt       DateTime?n' +
        '  createdAt         DateTime  @default(now())n' +
        '  updatedAt         DateTime  @updatedAtn' +
        '  acceptedBy        Driver?   @relation(fields: [driverId], references: [id])n' +
        '  offers            Offer[]n' +
        '}n' +
        'n' +
        'model Offer {n' +
        '  id        String   @id @default(uuid())n' +
        '  bookingId Stringn' +
        '  driverId  Stringn' +
        '  fare      Floatn' +
        '  status    String   @default("pending")n' +
        '  createdAt DateTime @default(now())n' +
        '  updatedAt DateTime @updatedAtn' +
        '  booking   Booking  @relation(fields: [bookingId], references: [id], onDelete: Cascade)n' +      
        '  driver    Driver   @relation(fields: [driverId], references: [id], onDelete: Cascade)n' +       
        '}n' +
        'n' +
        'model Admin {n' +
        '  id            String  @id @default(uuid())n' +
        '  email         String  @uniquen' +
        '  isOtpVerified Boolean @default(false)n' +
        '}n' +
        'n' +
        'model Otp {n' +
        '  id        String   @id @default(uuid())n' +
        '  email     Stringn' +
        '  otp       Stringn' +
        '  phone     String?n' +
        '  createdAt DateTime @default(now())n' +
        '  expiresAt DateTimen' +
        '}n' +
        'n' +
        'model Notification {n' +
        '  id        String   @id @default(uuid())n' +
        '  title     Stringn' +
        '  message   Stringn' +
        '  type      Stringn' +
        '  recipient Stringn' +
        '  data      Jsonn' +
        '  read      Boolean  @default(false)n' +
        '  createdAt DateTime @default(now())n' +
        '}n',
      overrideDatasources: {},
      inlineDatasources: [Object],
      

I can’t get the “minimal” example of BIMSurfer v3 to work

I am trying to run the “minimal” BIMSurfer v3 example included in the latest BIMServer version. I have configured the URL to the server, the login credentials, and the project ID appropriately. After enabling the debug flag, I noticed in the browser console that both the login and project retrieval occurred successfully with no reported errors. However, it doesn’t download the 3D model, so nothing shows up on the canvas.

Is something missing? Do you have any suggestions for addressing the problem?

The TS version of the project has not changed; Today, there was a sudden error when starting TS1110 TS1005 TS1128 [closed]

[tsl] ERROR in /Users/pxy/Projects/node_modules/@types/react-router/ts4.6/index.d.ts(124,100)
TS1110: Type expected.

error in /Users/pxy/Projects/node_modules/@types/react-router/ts4.6/index.d.ts

[tsl] ERROR in /Users/pxy/Projects/node_modules/@types/react-router/ts4.6/index.d.ts(124,109)
TS1005: ‘}’ expected.

error in /Users/pxy/Projects/node_modules/@types/react-router/ts4.6/index.d.ts

[tsl] ERROR in /Users/pxy/Projects/node_modules/@types/react-router/ts4.6/index.d.ts(124,114)
TS1128: Declaration or statement expected.

error in /Users/pxy/Projects/node_modules/@types/react-router/ts4.6/index.d.ts

[tsl] ERROR in /Users/pxy/Projects/node_modules/@types/react-router/ts4.6/index.d.ts(124,115)
TS1128: Declaration or statement expected.

Greasemonkey/Tapermonkey userscript: Change relative links to absoulte links [duplicate]

A sample page:

https://www.rhymezone.com/r/rhyme.cgi?Word=much&org1=syl&org2=l&org3=y&typeofrhyme=perfect

contains many links, all of a particular class, that I need to change

A sample link:
https://www.rhymezone.com/r/d=dutch

Need to change it to this:
https://www.collinsdictionary.com/dictionary/english/dutch

(Using Tapermonkey on Firefox)

The page source shows this:
<a class="r dispr" href="/r/d=dutch">dutch</a>

So I try this:

// ==UserScript==
// @name Rhymezone Definition Links Modifier
// @description Redirect a rhymezone page's definition links from rhymezone to collinsdictionary.com
// @include https://www.rhymezone.com/r/*
// @version 1
// @grant none
// ==/UserScript==

function rewriteLinks()
{
var coll = document.getElementsByClassName('r dispr');
var l = coll.length;
for (var i=0; i<l; i++)
    {
        coll[i].href=coll[i].href.replace("/r/d=","https://www.collinsdictionary.com/dictionary/english/");
    }

}
rewriteLinks();

Which gives, on hover over & click on the word “dutch”:

https://www.rhymezone.comhttps//www.collinsdictionary.com/dictionary/english/dutch

Instead of:

https://www.collinsdictionary.com/dictionary/english/dutch


How to fix this?

Spotfire toggle shuffles back to left while navigating to different page

I’m encountering an issue with a toggle switch embedded inside a text area that allows users to switch between viewing the top 15 and bottom 15 sales on a bar chart. The logic for toggling between these two views works correctly. However, when I navigate away from this page and return, the toggle UI resets to the default “Top 15” position—even if I had previously selected “Bottom 15.” Despite this, the bar chart continues to display the bottom 15 values, leading to a mismatch between the toggle’s position and the chart’s data.

Text area code:-

this is a script of a text area 
<!-- Toggle UI Styles -->
<style>
.switch {
  position: relative;
  display: inline-block;
  width: 70px;
  height: 34px;
}
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}
.slider {
  position: absolute;
  cursor: pointer;
  top: 0; left: 0; right: 0; bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 34px;
}
.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: Black;
  transition: .4s;
  border-radius: 50%;
}
input:checked + .slider {
  background-color: #f44336;
}
input:checked + .slider:before {
  transform: translateX(36px);
}
.label-text {
  font-family: Arial;
  font-size: 14px;
  margin: 0 10px;
}
.toggle-container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}
</style>



<!-- Toggle UI -->
<div class="toggle-container">
  <span class="label-text">Top 15</span>
  <label class="switch">
    <input type="checkbox" id="rankToggle">
    <span class="slider"></span>
  </label>
  <span class="label-text">Bottom 15</span>
</div>

<!-- Hidden buttons bound to IronPython scripts -->
<div style="display:none;">
<button id="setTop15" style="display:none;">Top</button>
<SpotfireControl id="0205d8e5efe047d5b9b8e885f864704f" />

<button id="setBottom15" style="display:none;">Bottom</button>
<SpotfireControl id="14d7f5c3deed4295af212cfacba2479d" />
</div>

<script>
document.getElementById("rankToggle").addEventListener("change", function() {
  if (this.checked) {
    document.getElementById("14d7f5c3deed4295af212cfacba2479d").click();
  } else {
    document.getElementById("0205d8e5efe047d5b9b8e885f864704f").click();
  }
});
</script>

On barchart, we have  Styles on x axis and Sum([TY Net Sales$]) on Y axis. 
Data limit using expression of bar chart is 
${TimeToggle} and If(
    Not ${RankSelectionToggleN},
    [SalesRank] <= 15,
    [SalesRank] >= (Max([SalesRank]) - 15 + 1)
)

SaleRank:- DenseRank(Sum(If(${TimeToggle},[TY Net Sales$],NULL)) Over ([Style]),"desc")

IronPython Script for Top 15:- Document.Properties["RankSelectionToggleN"] = False

IronPython Script for Bottom 15:- Document.Properties["RankSelectionToggleN"] = True

Any help would be greatly appreciated.

Thanks

Expecting toggle to work perfectly regardless of navigation across different pages

Right alt functioning differently in Windows and ubuntu

I was trying to implement a full screen functionality using javascript. I just want to enter full screen by ‘f’ key only.Have written a function to implement this:

function shortcutsHandler(event) {
      const isModifierKeyHeld = event.ctrlKey || event.altKey || event.metaKey || event.shiftKey;

      if (event.key === 'f' && !isModifierKeyHeld) {
        enterFullScreen();
        return;
      }
    }

This is working fine in Ubuntu systems. One of my colleagues using Windows 11 system found that right alt + f is going full screen in his system.
How can I get this resolved?
Any solutions is highly appreciated.

Breadcrumbs in PageContainer in MaterialUI

There is a problem with rendering breadcrumbs:

I had this code:


import {AppProvider, Navigation, PageContainer} from '@toolpad/core';


const AdminLayout = () => {

  const NAVIGATION:Navigation = [
    {
      title: 'Home',
      segment: '',
    },
    {
      title: 'Users',
      segment: 'users',
      children: [
        {
          title: 'User list',
          segment: 'list',
        }
      ]
    }
  ];

  return (
    <AppProvider
      navigation={NAVIGATION}
    >
      <PageContainer>
        <div>
          page content
        </div>
      </PageContainer>
    </AppProvider>
  );
};

export default AdminLayout;


And result on main page:

result on main page

Result of inner page:

result of inner page

And if I remove this part:

    {
      title: 'Home',
      segment: '',
    },

then breadcrumbs are not showing

Can somebody help to show valid breadcrumbs of all pages?

CORS Error 405 (Method Not Allowed) – Google App Scripts

I have a very simple webpage, that only has a button which should submit the POST below to my google app scripts code. When testing, I click the button to run the SendTest() function and get the following error in the console:

Access to fetch at ‘https://script.google.com/macros/s/[redacted]/exec’ from origin ‘http://127.0.0.1:5500’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

On the Network tab, I see the OPTIONS request, but it returns a 405 Method Not Allowed error. I have tried manually adding the header with no luck.

Any point in the right direction would be greatly appreciated.

Simplified HTML / JS Code:

<!DOCTYPE html>
<button onclick="sendTest()">Send Test POST</button>
<script>
async function sendTest() {
  try {
    const payload = {
      responses: [
        { category: 'Test', question: 'Q?', recommendation: 'Do X' }
      ]
    };

    console.log('Sending:', JSON.stringify(payload));

    const response = await fetch('https://script.google.com/macros/s/[redacted]/exec', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(payload),
      mode: 'cors',
      credentials: 'omit'
    });

    console.log('Response status:', response.status);
    console.log('Response headers:', [...response.headers.entries()]);

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`HTTP error! Status: ${response.status}, Details: ${errorText}`);
    }
    const result = await response.json();
    console.log('Response:', result);
  } catch (error) {
    console.error('Fetch error:', error);
  }

}

Google App Script Code:

function doGet(e) {
var output = JSON.stringify({
status: 'success',
message: 'It worked',
});

return ContentService.createTextOutput(output)
.setMimeType(ContentService.MimeType.JSON);
}
function doPost(e) {
 return ContentService.createTextOutput(JSON.stringify({status: "success", "data": "my-data"})).setMimeType(ContentService.MimeType.JSON);
}
function doOptions(e) {
  const output = ContentService.createTextOutput('');
  output.setMimeType(ContentService.MimeType.TEXT);
  output.addHeader('Access-Control-Allow-Origin', '*');
  output.addHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
  output.addHeader('Access-Control-Allow-Headers', 'Content-Type');
  return output;
}

Vite / React – Package imports a file without a default export (UMD vs ES6). Can I force a default export through vite configuration?

I am working on a Vite / React application which has a pretty typical setup. I now need to integrate with an older package and I’m running into some issues. The package has code like this in a js file:

Promise.all([import('another-package/dist/js/jsFile')])
          .then(([sdk]) => {
            const mySdk = sdk.Sdk()
            doSomethingWith(mySdk)
          })

When this code is run, I get sdk.Sdk() is not a function. When I modify the code through local testing like below, I get a successful load.

const mySdk = sdk.default.Sdk()

So I believe this whole issue is about default exports. And from what I have been reading, the package being referenced, “another_package”, is a UMD modul. Which does not necessarily work out of the box when being imported from an ES6 module because there is no default export from the UMD module. (I may be off base here, so feel free to correct me if I got this wrong).

I’ve been looking into vite configuration changes I can make to solve this issue but I can’t quite figure it out. I’ve been especially looking at the “rollup/plugin-commonjs” package because it seems to be what could solve this issue. Any advice is greatly appreciated.

How can I “force” the default export to be assumed from the package I am integrating with without modifying the package code?

problem dynamically modifying the ‘auto’ value of the css property of ‘grid-template-column’ with javascript

It’s been a game changer learning to learn to use javascript and the DOM to modify css classes from an external stylesheet. For the most part it works fine. In my snippet, changing the background-color to yellow works fine. But when i try to modify the value of ‘grid-template-column’ – no go. I’m trying to change the value to … ‘auto, auto, auto’, but it won’t overwrite the original value inside the style sheet, which looks like this.. ‘grid-template-columns: auto auto auto auto auto auto;’

Thanks in advance.

       // create a reference to linked stylesheet
        const stylesheet = document.styleSheets[0];
        const rules = stylesheet.cssRules || stylesheet.rules; 
        
        // loop through the style sheet reference to find the classes to be modified and modify them

        for (let i = 0; i < rules.length; i++) {
            if (rules[i].selectorText === '.grid-container') {
                rules[i].style['background-color'] ='yellow';
                rules[i].style['grid-template-column'] = 'auto auto auto';
                break;
            }
        }
        

Fetch API is not successful on ios safari

for some reason, this works totally fine on android/windows or any device except when trying to view it on ios/iphone safari. the data wont be loaded. I even tried and made the API into a local JSON file, and still it wont read it.

What seems to be the issue? One issue is I don’t have a Mac to diagnose the problem, so how do I go around this issue with iOS? Thanks

async function loadQuranData() {
    try {
        // Load Quran text from API
        const quranResponse = await fetch('https://api.alquran.cloud/v1/quran/quran-uthmani');
        if (!quranResponse.ok) {
            throw new Error(`Failed to load Quran data: ${quranResponse.status}`);
        }
        const quranJson = await quranResponse.json();
        
        // Validate Quran data structure
        if (!quranJson.data || !quranJson.data.surahs) {
            throw new Error('Invalid Quran data format');
        }
        
        quranData = quranJson.data.surahs;
        
        // Populate surah select immediately after loading Quran data
        const select = document.getElementById('surahSelect');
        if (!select) {
            throw new Error('Surah select element not found');
        }
        
        // Clear existing options
        select.innerHTML = '<option value="">' + languages[currentLang].selectSurah + '</option>';
        
        // Create options for each surah
        quranData.forEach((surah, index) => {
            const option = document.createElement('option');
            option.value = index;
            option.textContent = `${surah.number}. ${surah.name}`;
            select.appendChild(option);
        });
        
        // Remove any existing event listeners
        const newSelect = select.cloneNode(true);
        select.parentNode.replaceChild(newSelect, select);
        
        // Add the event listener
        newSelect.addEventListener('change', (e) => {
            if (e.target.value !== '') {
                currentSurah = parseInt(e.target.value);
                currentAyah = 0;
                isReadingMode = false;
                document.getElementById('btnReadingMode').innerHTML = '<i class="fas fa-book-open"></i>';
                displayAyah();
            } else {
                resetQuranContent();
            }
        });

Tried 3 AI code bots, tried to make the API return into a JSON file and make it read it manually, and still won’t. Thanks

RxDB update operations fail with “proxy must report the same value for the non-writable, non-configurable property ‘”_meta”‘

I am trying to get RxDB to let me put items into a database, show them reactively using Vue, and update their values based on user input from the browser. It seems like a pretty typical use case but I can’t figure it out.

<template>
  <q-page class="flex flex-center">
    <div>
      <p>content is here</p>
      {{currentState}}
      <q-btn @click="setLang()">
      </q-btn>
    </div>
  </q-page>
</template>

<script setup>

import { onMounted, ref, toRaw } from 'vue';

import { createRxDatabase, removeRxDatabase } from 'rxdb';
import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage';

import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode';
import { RxDBUpdatePlugin } from 'rxdb/plugins/update';
import { addRxPlugin } from 'rxdb/plugins/core';

import { wrappedValidateAjvStorage } from 'rxdb/plugins/validate-ajv';

addRxPlugin(RxDBDevModePlugin);
addRxPlugin(RxDBUpdatePlugin);

const dbHandle = ref();
const currentState = ref();

onMounted(async function () {
  console.log("mount");
  const storage = wrappedValidateAjvStorage({ storage: getRxStorageLocalstorage(), });
  removeRxDatabase('myDB', storage);

  let db = await createRxDatabase({
    name: 'myDB',
    storage: storage,
    multiInstance: true,
    eventReduce: true,
  });

  await db.addCollections({
    state: {
      schema: {
        title: 'state schema',
        version: 0,
        primaryKey: 'name',
        type: 'object',
        properties: {
          name: {
            type: 'string',
            maxLength: 100,
          },
          currentLanguage: { type: 'string' },
          count: {type: 'integer'},
        },
      },
    },
    });

  //set initial language to dutch
  await db.state.insert({
    name: "state",
    currentLanguage: "dutch",
    count: 0,
  });

  dbHandle.value = db;

  //query the single item that's in the table and track it reactively
  const state = dbHandle.value.state.findOne();
  state.$.subscribe((result) => {
    currentState.value = result;
  });
  console.log("done with mount");
});

//this is what happens when you click the UI button
async function setLang (evt)
{
  console.log("clicked");
  //find the single item and print its values
  const si = await dbHandle.value.state.findOne().exec();
  if (si != null)
  {
    console.log("SINFO: " + si.name + " " + si.currentLanguage + " " + si.count);
    console.log(toRaw(si));
  }
  else
  {
    console.log("it's null");
  }
  await si.patch({ currentLanguage: "french" });
}

</script>

I expected that clicking the UI button would cause the single tuple in the database to update its value from ‘dutch’ to ‘french’, and then this change would appear onscreen.

However, instead I get the error “Uncaught TypeError: proxy must report the same value for the non-writable, non-configurable property ‘”_meta”‘ ” (the call stack indicates that it originate in async code that I didn’t write: rx-query.ts:535).

Full call stack:

Uncaught TypeError: proxy must report the same value for the non-writable, non-configurable property '"_meta"'
    deepFreeze utils-object.ts:9
    deepFreeze utils-object.ts:7
    deepFreezeWhenDevMode index.ts:62
    rxChangeEventToEventReduceChangeEvent rx-change-event.ts:51
    calculateNewResults event-reduce.ts:133
    __ensureEqual rx-query.ts:602
    _ensureEqualQueue rx-query.ts:535
    utils-object.ts:9:44

(Mozilla Firefox 136.0.4)

Current packages installed from packages.json:

  "dependencies": {
    "@quasar/extras": "^1.16.4",
    "pouchdb": "^9.0.0",
    "quasar": "^2.16.0",
    "rxdb": "^16.12.0",
    "rxjs": "^7.8.2",
    "vue": "^3.4.18",
    "vue-router": "^4.0.0"
  },

I created a generic vue/quasar project using `npm init quasar’ and this is my only user-written component.