Is it possible to somehow interact with DOM during the beforeunload event? [closed]

I want to track page refresh or tab closing via the beforeunload event, but I don’t quite understand how it works? I can’t track the user’s cancellation and apply the DOM change before the pop-up window, maybe this is not possible?

I want to do the following. When trying to reload the page or leave it, I call beforeunload with the functions e.preventDefault() and e.returnValue = false, I want to blur the page content, and when the user cancels the action (i.e. he remains on the page further) remove the blur. Is this even possible to do?

For example, the confirm() function can return true or false, and I can track this, so what should I do with beforeunload?

In this example, the styles are applied after “Cancel” the page update in the dialog box. Is it possible to somehow change the styles BEFORE the dialog box appears, or is it impossible to do this? And is it possible to track the cancellation of the update, i.e. pressing the “Cancel” button in the dialog box, to remove these styles.
The example in the link in the comment gives a policy error.

UPD:
Here’s what I tried to do:

$(window).on('beforeunload', function(e) {
  if ($('#switch').is(':checked')) {
    e.preventDefault()
    e.returnValue = false
    $('.box').css({
      'filter': 'blur(10px)',
      '-webkit-filter': 'blur(10px)',
      '-moz-filter': 'blur(10px)',
      '-o-filter': 'blur(10px)',
      '-ms-filter': 'blur(10px)'
    });
  }
})
<label><input type="checkbox" id="switch" checked> Switch</lable>
<button onclick="location.reload()">Reload Page</button>
<h2 class="box">Page Content</h2>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

Performance difference between ObjectAssignmentPattern and ArrayAssignmentPattern [duplicate]

is there any performance or optimisation in v8 lvl difference between these two blocks of code?

// ArrayAssignmentPattern
const [firts, second] = await Promise.all([
  fetch('https://api.example.com/first'),
  fetch('https://api.example.com/second')
])

And

// ObjectAssignmentPattern
const { 0: third, 1: fourth } = await Promise.all([
  fetch('https://api.example.com/first'),
  fetch('https://api.example.com/second')
])

I’m not big fun of benchmarking via loop with 1_000_000 iteration, and not really can read bytecode, so i would like to clarify whether these two will work similarly or not.

AM Charts 4 scrollbars and zoom button is not announced by screenreader

I am using AM Charts 4 in a large Vue 3 application.

I am trying to make the screenreader announce all of the elements inside an XYChart.

The chart container has aria-live="polite" and when I use keyboard and tab to the columns in the chart, the series category and value is announced by the screenreader. But when I tab to one of the zooming scrollbars, the screenreader is silent.

When I inspect the scrollbar object, I can see it has readerTitle set to Use TAB to select grip buttons or left and right arrows to change selection

Why is this text not read aloud by the screenreader? What do I need to do to make the screenreader read out the readerText because according to the am charts documentation this is “all you need to do”…

Is it possible to somehow interact with DOM during the beforeunload event?

I want to track page refresh or tab closing via the beforeunload event, but I don’t quite understand how it works? I can’t track the user’s cancellation and apply the DOM change before the pop-up window, maybe this is not possible?

I want to do the following. When trying to reload the page or leave it, I call beforeunload with the functions e.preventDefault() and e.returnValue = false, I want to blur the page content, and when the user cancels the action (i.e. he remains on the page further) remove the blur. Is this even possible to do?

For example, the confirm() function can return true or false, and I can track this, so what should I do with beforeunload?

Performance difference between ObjectAssignmentPattern and ArrayAssignmentPattern

is there any performance or optimisation in v8 lvl difference between these two blocks of code?

// ArrayAssignmentPattern
const [firts, second] = await Promise.all([
  fetch('https://api.example.com/first'),
  fetch('https://api.example.com/second')
])

And

// ObjectAssignmentPattern
const { 0: third, 1: fourth } = await Promise.all([
  fetch('https://api.example.com/first'),
  fetch('https://api.example.com/second')
])

I’m not big fun of benchmarking via loop with 1_000_000 iteration, and not really can read bytecode, so i would like to clarify whether these two will work similarly or not.

Why is statusUpdatedTime undefined in my Node.js/MongoDB app?

I’m working on a Node.js app with MongoDB (using Mongoose), and I’m trying to set or update a statusUpdatedTime field in a document. But when I check the document after the update, the field is either undefined or missing entirely.

Here’s the relevant part of my schema:

    const orderSchema = new mongoose.Schema({
        status: { type: String },
        statusUpdatedTime: { type: Date }
    });

Here’s how I’m trying to update it:

    await Order.findByIdAndUpdate(orderId, {
        status: 'Shipped',
        statusUpdatedTime: new Date()
    });

But when I retrieve the document afterward, statusUpdatedTime is not set:

    const updatedOrder = await Order.findById(orderId);
    console.log(updatedOrder.statusUpdatedTime); // undefined

I’ve double-checked the field name, and the schema is correctly defined (I think). There are no errors during the update. The status field is being updated correctly, just not statusUpdatedTime.

What could be the cause of this? Is there something wrong in my schema, the update call, or somewhere else?

Environment:

  • Node.js v18.17.1

  • Mongoose v7.6.1

  • MongoDB v6.0

Thanks in advance!

Laravel 12 & Sanctum

im using Laravel 12 with sanctum and try to get a login via Angular Frontend.
Until now, im able to register and also get a positive response for the csrf token.
For the login, I got an 500er error with the “message”: “Session store not set on request.”

I tried with the previous hints for this error message, but didnt helped. Does anybody have some hints for me?

my request inside of angular looks like this:

login(data: { email: string; password: string }): Observable<User> {
  const headers = new HttpHeaders({
  'Accept': 'application/json',
  'Content-Type': 'application/json'
});
return this.http.get("http://localhost:8000/sanctum/csrf-cookie", { headers: headers, withCredentials: true }).pipe(
  switchMap(() =>
    this.http.post<User>(`${this.baseUrl}/login`, data, {
      headers: headers,
      withCredentials: true,
    })
  )
);}

This is my laravel api.php router

Route::post('/login', function (Request $request) {
$credentials = $request->only('email', 'password');

if (Auth::attempt($credentials)) {
    $request->session()->regenerate();

    return response()->json([
        'message' => 'Login erfolgreich',
        'user' => Auth::user() // Aktuell eingeloggter User
    ]);
}

return response()->json(['message' => 'Unauthorized'], 401);
});

This is my middleware inside of app.php

->withMiddleware(function () {


    return [

        // 1. Laravel interner Support für Precognitive-Requests
        IlluminateFoundationHttpMiddlewareHandlePrecognitiveRequests::class,

        // 2. Session starten (wichtig für Sanctum + Login)
        IlluminateSessionMiddlewareStartSession::class,

        // 3. Sanctum Middleware, die API-Requests als "stateful" behandelt
        LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,



        // 5. Eigene globale Middleware (z. B. zusätzliche CORS Header)
        function (IlluminateHttpRequest $request, Closure $next) {
            $response = $next($request);

            $response->headers->set('Access-Control-Allow-Origin', 'http://spa.localhost:4200');
            $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
            $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
            $response->headers->set('Access-Control-Allow-Credentials', 'true');

            return $response;
        },
    ];
})

My cors.php

<?php
return [

// Erlaube nur relevante Pfade
'paths' => ['api/*', 'sanctum/csrf-cookie'],
// Erlaube alle HTTP-Methoden (GET, POST, etc.)
'allowed_methods' => ['*'],
// Erlaube nur deine Angular-App
'allowed_origins' => ['http://spa.localhost:4200'],
// Kein Pattern nötig, da Origin explizit erlaubt
'allowed_origins_patterns' => [],
// Alle Header erlauben (z. B. Content-Type, X-XSRF-TOKEN, etc.)
'allowed_headers' => ['*'],
// Keine speziellen Header müssen offengelegt werden
'exposed_headers' => [],
// Preflight-Caching (kann bei Bedarf höher gesetzt werden)
'max_age' => 0,
// Damit Cookies (Sessions) mitgeschickt werden dürfen
'supports_credentials' => true,
];

And my env:

SANCTUM_STATEFUL_DOMAINS=spa.localhost:4200
SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=.localhost

php function that downloads empty files [closed]

I have a problem with a function that is supposed to download. Why are empty files being downloaded? Where am I going wrong? Thank you all.

I pass the name of the file I need to download to the function.

function downloadAttachmentKb($filesDownload)
{
    if (empty($filesDownload)){
        return false;
    }
    
    set_time_limit(0);
    $DownloadDir = "./files/kbfiles/".$filesDownload ;
    $DownloadFiles = basename( $filesDownload);
    $DovnloadSize = filesize( $DownloadDir);
    
    if (!file_exists($DownloadDir) && !is_writable($DownloadDir)){
        die("errore");
    }
    
    $MimeFile = mime_content_type($DownloadDir);
    
    if ($MimeFile === false){
        header("Content-Type: application/force-download");
    }else{
        header(header: "Content-Type:".$MimeFile."");
    }
    
    if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")){
        header("Content-Disposition: inline ; filename="". $DownloadFiles.""");
    } else{
        header(header: "Content-Disposition: attachment; filename="". $DownloadFiles .""");
    }
    
    header(header: "Content-Length: ". filesize($DownloadDir));
    header("Content-Description: File Transfer");
    header("Content-Transfer-Encoding: binary");
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: public");
    ob_clean();
    flush();
        
    echo file_get_contents($DownloadDir);
    
}
?>

Unable to open a browser when call is accepted [closed]

I am triggering a call from postman to mobile phone using twilio. I am able to call successfully. It rings on my phone. When I click accept, a message is prompted on the call. When I press 1, it says something error and does not redirect or open a website link.

How should I open a browser and display the url as passed?

 <?php

 namespace AppHttpControllers;

 use IlluminateHttpRequest;
 use TwilioRestClient;

class TwilioController extends Controller
{
public function makeCall(Request $request)
{
    $sid    = env('TWILIO_ACCOUNT_SID');
    $token  = env('TWILIO_AUTH_TOKEN');
    $twilio = new Client($sid, $token);

    $call = $twilio->calls->create(
        $request->input('to'), // User's phone number in E.164 format
        env('TWILIO_PHONE_NUMBER'), // Your Twilio number
        [
            'url' => 'http://testing.domain.tech/twilio/voice-prompt'
        ]
    );

    return response()->json(['status' => 'Call initiated', 'sid' => $call->sid]);
}

public function voicePrompt()
{
    $response = new TwilioTwiMLVoiceResponse();

    $gather = $response->gather([
        'numDigits' => 1,
        'action' => url('/twilio/handle-key-press'),
        'method' => 'POST'
    ]);
    $gather->say('Press 1 to receive a link via SMS.');

    // If no input, Twilio will call this after gather timeout
    $response->say('No input received. Goodbye!');
    
    return response($response)->header('Content-Type', 'text/xml');
}


public function handleKeyPress(Request $request)
{
    $digits = $request->input('Digits');
    $from = $request->input('From');
    $response = new TwilioTwiMLVoiceResponse();

    if ($digits == '1') {
        try {
            $sid    = env('TWILIO_ACCOUNT_SID');
            $token  = env('TWILIO_AUTH_TOKEN');
            $twilio = new Client($sid, $token);

            $twilio->messages->create(
                $from,
                [
                    'from' => env('TWILIO_PHONE_NUMBER'),
                    'body' => 'Here is your link: ' . url('/')
                ]
            );
            $response->say('A link has been sent to your phone via SMS. Thank you!');
        } catch (Exception $e) {
            Log::error('Twilio SMS error: ' . $e->getMessage());
            $response->say('Sorry, there was an error. Please try again later.');
        }
    } else {
        $response->say('Invalid option. Goodbye!');
    }

    return response($response)->header('Content-Type', 'text/xml');
 }
}

// web.php

Route::post('/twilio/voice-prompt', [TwilioController::class, 'voicePrompt'])->name('twilio.voicePrompt');
Route::post('/twilio/handle-key-press', [TwilioController::class, 'handleKeyPress'])->name('twilio.handleKeyPress');

// api.php

Route::post('/twilio/make-call', [TwilioController::class, 'makeCall']);

faild to install PHP 8.3 on Ubuntu 20.04 [closed]

I want to install php8.3 on Ubuntu 20.04.6. but

sudo apt-get install php8.3

returns :

E: Unable to locate package php8.3
E: Couldn't find any package by glob 'php8.3'
E: Couldn't find any package by regex 'php8.3'

what to do?

lsb_release -a

returns :

No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.6 LTS
Release:    20.04
Codename:   focal

apt policy php8.3 and apt-cache search php8.3 returns nothing


I added ppa:ondrej/php repository.

cat /etc/apt/sources.list.d/ondrej-ubuntu-php-focal.list

returns

deb http://ppa.launchpad.net/ondrej/php/ubuntu focal main
# deb-src http://ppa.launchpad.net/ondrej/php/ubuntu focal main

in fact on a machine php8.3 is installed but when trying to install extension php8.3-gmp on it ,can not find

load image in select dropdown list

I have a dropdown list, here in the option I want to load image also. I took reference from:
i want to display image in select option dynamically but not working

But the image is not loading. The path of image file is correct.

<select name="n_bundle_num" class="form-control" required>
    <option>--- select budle ---</option>
    @foreach ($bundles as $item)
        <option value="{{ $item->name }}" 
            data-subtext="<img src='/bundles/{{ $item->image_path }}'>">{{ $item->name }}
        </option>
    @endforeach
</select>

Webpack Module Federation infinite reload

I try to split my angular 20 monolith and seperate my blogs from my main app. I set up everything but whatever I do, as soon as the remote gets fetched my application keeps on refreshing infinitely. Here my webpack configurations:

SHELL:

const { withModuleFederationPlugin, shareAll } = require('@angular-architects/module-federation/webpack');


const config = withModuleFederationPlugin({
  name: 'host',
  exposes: {},
  remotes: {
    blog: 'blog@localhost:4201/remoteEntry.js',
  },
  shared: {
  }
});

config.output.uniqueName = 'shell';
config.optimization.runtimeChunk = false;

module.exports = config;

REMOTE:

const { withModuleFederationPlugin } = require('@angular-architects/module-federation/webpack');

const config = withModuleFederationPlugin({
  name: 'blog',
  filename: 'remoteEntry.js',
  exposes: {
    './BlogLandingPageComponent': './projects/blog/src/app/blog/blog-landing-page/blog-landing-page.component',
    './BlogService': './projects/blog/src/app/blog/blog.service',
  },
  shared: {
  },
  remoteType: 'var',
  library: {
    type: 'var',
    name: 'blog'
  },

});

config.output = {
  chunkFormat: 'array-push',
  chunkLoading: 'jsonp',
  uniqueName: 'blog',
  publicPath: "auto", // Use auto public path for dynamic loading
  scriptType: 'text/javascript'
};

config.optimization = {
  runtimeChunk: false,
};

module.exports = config;

Then, in my main.ts I try to initialize the remote like:

 Promise.all([
    loadRemoteEntry({
      type: 'script',
      remoteEntry: "http://localhost:4201/remoteEntry.js",
      remoteName: 'blog'
    }),
  ])
    .catch((err) => console.error('Error loading remote entries', err))
    .then((val) => {

      console.log('Remote entry loaded successfully:', val);

      // Check if the remote container is available
      if (window['blog']) {
        console.log('✅ Remote container "blog" is available:', window['blog']);
      } else {
        console.error('❌ Remote container "blog" is NOT available!');
      }

      if (document.readyState === 'complete') {
        bootstrap();
      } else {
        document.addEventListener('DOMContentLoaded', bootstrap);
      }
    })

Commenting out the loadRemoteEntry method the refresh loop disappears. Is it an issue of hmr (hot module reloading)?

Why is window.opener null when opening a popup from React app (localhost:8000) to another origin (localhost:3000)?

I’m trying to implement Microsoft SSO login in a React frontend ("http://localhost:8000") by opening a popup to a backend server ("http://localhost:3000") that handles the auth redirect.

Here’s the setup:

  • Frontend (React, using react-scripts start) runs at "http://localhost:8000"
  • Backend (Node.js + Express) runs at "http://localhost:3000"
  • After login, the backend redirects to a static file microsoft-login-success.html inside public/

In the React code, I open the popup like this:

const popup = window.open(
  "http://localhost:3000/microsoft-login-success.html",
  "loginPopup",
  "width=600,height=600"
);

Inside microsoft-login-success.html, I have: (Actually this script in a file js because policy of browser)

<script>
  window.onload = () => {
    alert("Loaded popup");
    console.log("window.opener:", window.opener); // This logs "null"
    window.opener?.postMessage("ready", "http://localhost:8000");
  };
</script>

What I’ve tried:

  • Using “*” or full origin in postMessage() — no difference
  • Confirmed CORS is configured correctly
  • No browser extensions interfering
  • Tested on multiple browsers

Problem:

window.opener is null in the popup page so postMessage() back to the frontend doesn’t work/

Notes:

I confirmed that the popup opens from window.open(), not from a <a> tag. This works fine if I open window.open() between 2 plain HTML pages. Only when running React via react-scripts start does window.opener become null in the popup.

  • Why is window.opener null in the popup when opened from a React app running on "localhost:8000" to a static page served on "localhost:3000"?
  • Is this caused by react-scripts dev server, cross-origin issues, or security headers?
  • What’s the correct way to communicate from popup to parent across "localhost:8000" and "localhost:3000"?

Updated:

app.use((req, res, next) => {
  res.setHeader("Cross-Origin-Opener-Policy", "unsafe-none");
  res.setHeader("Cross-Origin-Embedder-Policy", "unsafe-none");
  next();
});

I have to allow Cross-Origin on the BE side so they can communicate through postMessage.
If you want to check your website is allowed or not, just F12 then go to Network tab, check the Response Header/ Request Header

Javascript client is failing to connect to (ws, not wss) websocket (definitely a client-side issue)

So im trying to integrate my first websocket, to work on a basic chat system.

My main issue is, I cant get the client to connect to the socket.

However I can connect when using websocat on 127.0.0.1 host, this has allowed me to identify this as a client side issue. Please do let me know why this is happening, and should my client code look good, I am able to try this from another device as it may be, however likely isn’t, my connection causing the connection to break.

my chat.js:

// Debugging flag
let debugMode = true; // Set to false to disable console logs

// Function to format the date
function formatDate(dateString) {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) {
        return 'Invalid date'; // Handle invalid date
    }
    return date.toLocaleTimeString(); // Format the date to local time string
}


// Function to display messages in the chat UI
function displayMessage(message) {
    const messagesContainer = document.getElementById('messages');
    // Create message element
    const messageElement = document.createElement('div');
    messageElement.classList.add('flex', 'items-start', 'max-w-xs');

    // Check if the message is sent or received
    if (message.senderPublic === puba) { // Replace with actual public key
        messageElement.classList.add('ml-auto');
        messageElement.innerHTML = `
            <div class="ml-auto text-right">
                <div class="bg-blue-600 rounded-lg p-3 text-white">
                    ${message.message}
                </div>
                <p class="text-gray-500 text-xs mt-1 text-right">${formatDate(message.date)}</p>
            </div>
        `;
    } else {
        messageElement.innerHTML = `
            <img src="https://storage.googleapis.com/workspace-0f70711f-8b4e-4d94-86f1-2a93ccde5887/image/e359ba49-2440-4fce-934f-7d2db6d4d05b.png" alt="Sender" width="36" height="36" class="rounded-full mr-3 w-9 h-9">
            <div>
                <div class="bg-gray-700 rounded-lg p-4 text-gray-200 text-xl">
                    ${message.message}
                </div>
                <p class="text-gray-500 text-sm mt-2">${formatDate(message.date)}</p>
            </div>
        `;
    }

    // Append the message to the container
    messagesContainer.appendChild(messageElement);
    lastMessageId = message.id; // Update last message ID
}

// Function to request new messages
function requestNewMessages(socket) {
    socket.send(`messages ${lastMessageId}`);
    logDebug('Requested new messages');
}


// Debug logging function
function logDebug(...messages) {
    if (debugMode) {
        console.log(...messages);
    }
}


let lastMessageId = 0;
logDebug('WebSocket connection opening');
// Event listener for when the connection is opened

my tag on the actual page

<script>
    // Toggle dropdown visibility
    document.getElementById('createChatBtn').addEventListener('click', function() {
        const dropdown = document.getElementById('dropdown');
        dropdown.classList.toggle('hidden');
    });
    const socket = new WebSocket('ws://127.0.0.1:8080<%=request.getContextPath()%>/ws/chat/<%=Base64.getEncoder().encodeToString(request.getSession().getAttribute("token").toString().getBytes())%>/<%=chatId%>');
    const puba = '<%=wallet.getPublicKey()%>';
    socket.addEventListener('open', function (event) {
        logDebug('WebSocket connection opened & authenticated');
    });
    socket.addEventListener('message', function (event) {
        const messageData = JSON.parse(event.data);
        logDebug('Received message:', messageData);
        displayMessage(messageData);
    });
    socket.addEventListener('error', function (event) {
        console.error('WebSocket error:', event);
    });
    socket.addEventListener('close', function (event) {
        console.log('WebSocket connection closed:', event);
    });
    var millisecondsToWait = 10000;
    setTimeout(function() {
        setInterval(requestNewMessages(socket), 5000);
    }, millisecondsToWait);
</script>

My error dump:

(index):64 cdn.tailwindcss.com should not be used in production. To use Tailwind CSS in production, install it as a PostCSS plugin or use the Tailwind CLI: https://tailwindcss.com/docs/installation
(anonymous) @ (index):64
(anonymous) @ (index):64
chat.js:59 WebSocket connection opening
chat?id=33:146 WebSocket connection to 'ws://127.0.0.1:8080/5resrerw253/ws/chat/M2hpSmJkUCQ4JHJONiMj/33' failed: 
(anonymous) @ chat?id=33:146
chat?id=33:157 WebSocket error: Event {isTrusted: true, type: 'error', target: WebSocket, currentTarget: WebSocket, eventPhase: 2, …}isTrusted: truebubbles: falsecancelBubble: falsecancelable: falsecomposed: falsecurrentTarget: WebSocket {url: 'ws://127.0.0.1:8080/5resrerw253/ws/chat/M2hpSmJkUCQ4JHJONiMj/33', readyState: 3, bufferedAmount: 0, onopen: null, onerror: null, …}defaultPrevented: falseeventPhase: 0returnValue: truesrcElement: WebSocket {url: 'ws://127.0.0.1:8080/5resrerw253/ws/chat/M2hpSmJkUCQ4JHJONiMj/33', readyState: 3, bufferedAmount: 0, onopen: null, onerror: null, …}target: WebSocket {url: 'ws://127.0.0.1:8080/5resrerw253/ws/chat/M2hpSmJkUCQ4JHJONiMj/33', readyState: 3, bufferedAmount: 0, onopen: null, onerror: null, …}timeStamp: 4215.5type: "error"[[Prototype]]: Event
(anonymous) @ chat?id=33:157
chat?id=33:160 WebSocket connection closed: CloseEvent {isTrusted: true, wasClean: false, code: 1006, reason: '', type: 'close', …}
chat.js:51 WebSocket is already in CLOSING or CLOSED state.
requestNewMessages @ chat.js:51
(anonymous) @ chat?id=33:164
setTimeout
(anonymous) @ chat?id=33:163
chat.js:59 Requested new messages

Why does my debounce function not work correctly inside a component?

I’m trying to implement a debounce function in a React component to prevent multiple API calls while the user types in a search input field.

Here’s the debounce function I’m using:

function debounce(fn, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

And this is how I’m using it in my React functional component:

import React, { useState } from 'react';

function SearchComponent() {
  const [query, setQuery] = useState('');

  const handleChange = (e) => {
    setQuery(e.target.value);
    debouncedSearch(e.target.value);
  };

  const debouncedSearch = debounce((val) => {
    console.log('Searching for:', val);
    // Simulate API call here
  }, 500);

  return <input type="text" onChange={handleChange} />;
}

Wrapping debouncedSearch with useCallback

Moving the debounce function outside the component scope (which works but doesn’t have access to component state directly).

Using external libraries like lodash.debounce, but still facing similar behavior if declared inside the component.