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!

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.

Why does my debounce function not work correctly inside a React 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.

Why does setTimeout inside a loop print the same value? [duplicate]

I’m trying to understand how setTimeout works inside a loop in JavaScript. I expected it to print numbers from 1 to 5, each printed after one second, but instead, it prints the number 6 five times.

Here is the code I wrote:

for (var i = 1; i <= 5; i++) {
    setTimeout(() => {
        console.log(i);
    }, i * 1000);
}

I expected the output to be:

1
2
3
4
5

But instead, the output is:

6
6
6
6
6

I think this might be related to the way var works in JavaScript and how closures capture variables in asynchronous code. I would like to understand why this behavior occurs, and how I can modify the code so that it correctly prints numbers 1 through 5 with a one-second delay between each.

indesign js: How to apply link to a specific word within a textframe?

Currently I can only apply it to the whole textfield.

I want to be able to apply internal links to different pages to a specific word within a TextField, so I can have multiple links within the same textfield.

How would I get “LINK-A” and “LINK-B” to work to different destinations?


doc = app.activeDocument;
var layers = doc.layers;
var pages = doc.pages;
var firstPage = pages.item(0);

for (var i = 1; i < 6; i++) {
    var anotherPage = pages.add();
}
var tfPage1 = firstPage.textFrames.add();
tfPage1.geometricBounds = [2, 2, 20, 20];
tfPage1.contents = "yaddda yadda LINK-A yadda yaddanAnd a LINK-B on the 2nd line";

var linkA = layers[0].textFrames[0].texts[0]; // what goes here?
var hyperlinkSource1 = doc.hyperlinkTextSources.add(linkA);
hyperlinkDestination1 = doc.hyperlinkPageDestinations.add(pages.item(3));
doc.hyperlinks.add(hyperlinkSource1, hyperlinkDestination1);

var linkB = layers[0].textFrames[0].texts[0];  // what goes here?
var hyperlinkSource2 = doc.hyperlinkTextSources.add(linkB);
hyperlinkDestination2 = doc.hyperlinkPageDestinations.add(pages.item(2));
doc.hyperlinks.add(hyperlinkSource2, hyperlinkDestination2);


StaleElementReferenceError in Selenium when running in Docker but not Locally

For this apps test, doing a series of cucumber steps with the verification is in selenium. In the steps we hover over an element which causes a tooltip to pop-up. Selenium is then supposed to locate the element in the tooltip and check for it being displayed. When running this test locally the test completes successfully but when ran inside docker it results in a StaleElementReferenceError for the pop up.

    When User hovers over tooltip
    Then User sees the tooltip information

Which calls these two functions

    hoverOverTooltip() {
        return this.hover(locators.Tooltip);
    }

    verifyTooltipinfoIsDisplayed() {
        const locatorToVerify = {
            Mode: By.xpath('//span[contains(text(), 'Modes')]'),
            low: By.xpath('//span[contains(text(), 'Low')]'),
            high: By.xpath('//span[contains(text(), 'High')]'),
            medium: By.xpath('//span[contains(text(), 'Medium')]'),

        }
        return Promise.all([
            this.verifyElementIsDisplayed(locatorToVerify.Mode),
            this.verifyElementIsDisplayed(locatorToVerify.low),
            this.verifyElementIsDisplayed(locatorToVerify.high),
            this.verifyElementIsDisplayedAfterHover(locatorToVerify.medium),
        ])
    }

And this is the selenium checks

    async verifyElementIsDisplayed(locator) {
        const element = await this.app.page.findElement(locator);
        return element.isDisplayed();
    }

    async hover(locator) {
        const element = await this.app.page.findElement(locator);
        const actions = this.page.actions({async: true});
        await actions.move({origin: element}).perform();
    }

Running in Docker results in the error

   ✖ Then User sees the tooltip information # file:steps.js:60
       StaleElementReferenceError: stale element reference: stale element not found in the current frame
         (Session info: chrome=124.0.6367.243)
           at Object.throwDecodedError (/tests/node_modules/selenium-webdriver/lib/error.js:523:15)
           at parseHttpResponse (/tests/node_modules/selenium-webdriver/lib/http.js:524:13)
           at Executor.execute (/tests/node_modules/selenium-webdriver/lib/http.js:456:28)
           at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
           at async Driver.execute (/tests/node_modules/selenium-webdriver/lib/webdriver.js:745:17)
           at async SeleniumEditConnectionPage.verifyElementIsDisplayedAfterHover (file
           at async CustomWorld.<anonymous> (file)

I tried writing this monster of a function to try to re-find the element and re-hover over the tooltip, but it fails at trying to perform the action.move to re-hover over the element again and exits the function.

    async verifyElementIsDisplayedAfterHover(locator, hoverLocator) {
        try {
            await this.verifyElementIsDisplayed(locator);
        }
        catch (error) {
            if (error.name === 'StaleElementReferenceError') {
                console.log("StaleElementReferenceError caught");

                // Re-locate the hover element
                console.log("Re-locating hover element...");
                const hoverElement = await this.app.page.findElement(hoverLocator);

                // Re-hover
                console.log("Re-hovering...");
                const actions = this.app.page.actions({ async: true });
                console.log("Hover acction made");
                await actions.move({ origin: hoverElement, x: 1, y: 1 }).perform();
                console.log("Hover action completed");

                // Optional: small delay to allow DOM update
                await this.app.page.sleep(300); // or use setTimeout in a wrapper

                // Wait for the element to appear and be visible
                console.log("Waiting for element to be visible...");
                await this.app.page.wait(until.elementLocated(locator), 5000);
                const element = await this.app.page.findElement(locator);
                await this.app.page.wait(until.elementIsVisible(element), 5000);

                return element.isDisplayed();
            } else
                throw new Error(`Unable to find the '${locator}' on the window.n Returned error: '${error}'`);
        }
    }

Clip a canvas using a polygon and a blured circle

I try to clip an canvas using to different shape : a polygon (saying a star) and a blured circle (its edges fade-out from transparent to partially opaque).

Here is a sample of the code to make this clip but I’m totally unable to create the “blur effect” around the circle.

      const canvas = document.getElementById("canvas");
      const ctx = canvas.getContext("2d");

      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;

      const img = new Image();
      img.src = "https://picsum.photos/800/600";
      img.onload = function () {
        let mouseX = canvas.width / 2;
        let mouseY = canvas.height / 2;
        const radius = 70;

        function draw() {
          ctx.save();

          ctx.fillStyle = "rgba(0, 0, 0, 0.7)";
          ctx.fillRect(0, 0, canvas.width, canvas.height);

          const starPoints = createStar(5, mouseX, mouseY, 100, 50);
          ctx.beginPath();
          ctx.moveTo(starPoints[0].x, starPoints[0].y);
          for (let i = 1; i < starPoints.length; i++) {
          ctx.lineTo(starPoints[i].x, starPoints[i].y);
          }
          ctx.closePath();
          ctx.clip();

          const gradient = ctx.createRadialGradient(
            mouseX,
            mouseY,
            radius * 0.8,
            mouseX,
            mouseY,
            radius
          );
          gradient.addColorStop(0, "rgba(0, 0, 0, 0)");
          gradient.addColorStop(1, "rgba(0, 0, 0, 0.7)");

          ctx.fillStyle = gradient;
          ctx.beginPath();
          ctx.arc(mouseX, mouseY, radius, 0, Math.PI * 2);
          ctx.fill();

          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

          ctx.restore();
        }

        function createStar(points, cx, cy, outerRadius, innerRadius) {
          const result = [];
          const angleStep = Math.PI / points;
          for (let i = 0; i < 2 * points; i++) {
            const angle = i * angleStep - Math.PI / 2;
            const radius = i % 2 === 0 ? outerRadius : innerRadius;
            result.push({
              x: cx + radius * Math.cos(angle),
              y: cy + radius * Math.sin(angle),
            });
          }
          return result;
        }

        canvas.addEventListener("mousemove", function (event) {
          mouseX = event.clientX;
          mouseY = event.clientY;
          draw();
        });

        draw();
      };
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
      body {
        margin: 0;
        overflow: hidden;
      }
      canvas {
        display: block;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas"></canvas>
  </body>
</html>

I need to keep star edges sharp, but the circle edge fading-out

jquery – adding a div to a list of divs

So I have a structure like this on my page (greatly simplified):

<div id='full-list'>
    <div id='test-1'> STUFF ONE</div>
    <div id='test-2'> STUFF TWO</div>
    <div id='test-3'> STUFF THREE</div>
</div>

I have a handler function inside an ajax call that gets a new block of HTML as a string:

json.new_div_html = "<div id='test-4'> STUFF FOUR</div>";

I want to add it to the list above, so that I get:

<div id='full-list'>
    <div id='test-4'> STUFF FOUR</div>
    <div id='test-1'> STUFF ONE</div>
    <div id='test-2'> STUFF TWO</div>
    <div id='test-3'> STUFF THREE</div>
</div>

I tried using:

$('#full-list').prepend( json.new_div_html );

But that just does nothing – no error, no visible change to my page. Not sure what I’m doing wrong?

Demo…

const json = {};
json.new_div_html = "<div id='test-4'> STUFF FOUR</div>";

$('#full-list').prepend( json.new_div_html );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.slim.min.js"></script>
<div id='full-list'>
    <div id='test-1'> STUFF ONE</div>
    <div id='test-2'> STUFF TWO</div>
    <div id='test-3'> STUFF THREE</div>
</div>

Error uploading image to Firebase Storage with React Native Expo – (storage/unknown)

I’m trying to upload an image to Firebase Storage using React Native with Expo. The image is picked using expo-image-picker, and I’m getting the following error:

FirebaseError: Firebase Storage: An unknown error occurred, please check the error payload for server response. (storage/unknown)

What I’ve already done:
Firebase project is properly configured.
My Storage rules are set as follows:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}

The user is authenticated with Firebase before uploading.
Image URI is correctly returned by expo-image-picker (confirmed via console.log).
I’m converting the URI to a blob using fetch() and response.blob().

const handlePickImage = async () => {
  const result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.Images,
    quality: 0.7,
  });

  if (!result.canceled) {
    const response = await fetch(result.assets[0].uri);
    const blob = await response.blob();

    const storageRef = ref(storage, `avatars/${userId}.jpg`);

    try {
      await uploadBytes(storageRef, blob);
      console.log('Upload successful!');
    } catch (err) {
      console.error('Error uploading image:', err);
    }
  }
};

Passing parameter to route function from ajax

I am trying to call a controller method using ajax. But I do not know how to do it? I have tried several ways but can not find the right one.

My controller method::

use AppHttpControllersController;
use AppModelsAdminServicesPost;

public function edit(string $id)
    {
        $post = Post::find($id);
        return Response()->json($post);
    }

Route method::

Route::get('admin_post_edt/{id}', [PostController::class, 'edit'])->name('admin_post.edit');

Blade page::

{{-- removed other code --}}
<td>
    <button type="button" id="edit_btn" value="{{ $item->id }}" class=" btn btn-primary btn-sm"><i
            class="fa fa-edit"></i></button>   
</td>
<script>
$(document).on('click', '#edit_btn', function() {
            var post_id = $(this).val();
            $.ajax({
            type:"GET",
            url: "{{ route('admin_post.edit')}}",
            data: { id: post_id },
            dataType: 'json',
            success: function(res){
            $('#editModal').modal('show');
            },
            failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
            });
</script>

How to pass id to the route admin_post.edit?