Listening webhook and updating UI in Next js 15

I am listening webhook in next js by creating an API route api/webhook/order_created. The code is

export async function POST(request: Request) {
    const session = auth();

    if (!session) {
        return new Response('Unauthorized', {
            status: 401,
        })
    }

    try {
        const res = await request.json();

        if (res) {
            const order: OrderType | null = prepareOrder(res);

            if (!order) {
                return new Response('Order not created', {
                    status: 400,
                })
            }

            //connect to the database
            await dbConnect();

            //create a new order document in the database
            const newOrder = new Order(order);
            await newOrder.save();

            revalidatePath('/orders2');
            //send server side event to the client
            notifyListeners(order);

            return new Response('Success!', {
                status: 200,
            })
        } else {
            return new Response('', {
                status: 400,
            })
        }

        // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (error: any) {
        return new Response(`Webhook error: ${error.message}`, {
            status: 400,
        })
    }
}

Here I am revalidating the UI of the /orders2 page. But it is not refetching the fresh data from the DB and not updating the UI.

Here is my order page code:

import getOrders from '@/actions/woocommerce/getOrders'
import React from 'react'

async function page() {
    const orders = await getOrders();

    return (
        <div className='flex gap-4'>
            {
                orders.map(order => (
                    <div key={order.order_id}>
                        <h1>{order.order_id}</h1>
                        <p>{order?.amount}</p>
                    </div>
                ))
            }
        </div>
    )
}

export default page

Could you please guide me on how I can update the UI after receiving the webhook?

How to Implement a Smooth Transition Header with Disappear and Appear Animation?

I am trying to implement a smooth transition header similar to the animation in this reference: Reference Animation.

Here’s what I have tried so far: My Attempt.

My code is hosted on StackBlitz: My Code.

Header Details:

The header is divided into two sections:

Nav Section: Contains the logo, and close button.

Information Section: Displays data such as the points and other info may add.

Desired Behavior:

When scrolling to the bottom:

  1. The Nav Section should stick to the top of the header.
  2. The Information Section should smoothly and slowly disappear with an animation. As the Information Section disappears, its space should
    be taken over by the main content (e.g., lorem ipsum text) as part
    of an expand/collapse effect.

Issues I’m Facing:

  1. Scroll Detection: I’m not sure if I need scroll detection or if it’s implemented incorrectly in my current code.

  2. Header Rounding: The rounded edges of the header are not working as expected during the animation.

  3. Smooth Animation: I am unable to achieve the same smooth disappear/appear animation as shown in the reference.

  4. Expanding Behavior: The transition from the disappearing Information Section to the main content expanding into its place doesn’t look smooth.

What I’ve Tried:

Applied Tailwind’s transition classes for animation.
Used window.scrollY to detect scrolling, but I’m unsure if this is necessary or implemented correctly.
Attempted to add rounding with rounded-xl, but it’s not transitioning smoothly or at all.

Question:

How can I achieve the exact smooth transition and animation shown in the reference, with the expand/collapse behavior? Any suggestions or improvements to my approach would be greatly appreciated.

Phantom connect wallet on mobile

I try to open my web3 app on phantom wallet on the test vps, and its open the link in browser, dont open the phantom, or open only phantom not connect:

function openPhantomApp() {
    const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    if (isMobile) {
        // Otwieramy Phantom z poprawnym deeplinkiem
        const url = "https://185.229.225.225:3000"; 
        const ref = "myRef"; 
        window.location.href = `https://phantom.app/ul/browse/${encodeURIComponent(url)}?ref=${encodeURIComponent(ref)}`;
        setTimeout(() => {
            alert("Please make sure Phantom Wallet is installed on your device.");
        }, 1000);
    } else {
        alert("Phantom wallet is not available. Make sure it's installed and connected.");
    }
}

Please help, what im doing bad??

On browser extensions, works this one:

$('#connect-wallet').on('click', async () => {
    const selectedWallet = $('#wallet-selector').val();

    if (selectedWallet === 'phantom' && window.solana && window.solana.isPhantom) {
        await connectWallet(window.solana);
    } else if (selectedWallet === 'sollet' && window.sollet && window.sollet.isSollet) {
        await connectWallet(window.sollet);
    } else if (selectedWallet === 'solflare' && window.solflare && window.solflare.isSolflare) {
        await connectWallet(window.solflare);
    } else {
        alert("Selected wallet extension is not found.");
        promptToInstallExtension(selectedWallet);
    }
});

async function connectWallet(wallet) {
    try {

        const resp = await wallet.connect();
        console.log(`${wallet.name} connected:`, resp);


        const rpcEndpoint = 'https://mainnet.helius-rpc.com/?api-key=xxxxxxxxxxxxxxxxxxxxxxxxx';
        const connection = new solanaWeb3.Connection(rpcEndpoint, 'confirmed');


        const publicKey = new solanaWeb3.PublicKey(resp.publicKey);
        const walletBalance = await connection.getBalance(publicKey);
        console.log("Wallet balance:", walletBalance);


        const minBalance = await connection.getMinimumBalanceForRentExemption(0);
        console.log("Minimum rent exemption balance:", minBalance);


        if (walletBalance < minBalance) {
            alert("Insufficient funds for rent.");
            return;
        }


        $('#connect-wallet').text("Mint");
        $('#connect-wallet').off('click').on('click', async () => {
            await mintTransaction(resp.publicKey, walletBalance, minBalance, connection);
        });
    } catch (err) {
        console.error("Error connecting to wallet:", err);
    }
}

I think i need to open it on phantom and soflare browser, but nothing works, I dont know why.

I tried method from documentation, I think I do something bad ;/

Prettier @trivago/prettier-plugin-sort-imports fails to place .css imports at the bottom

I’m using @trivago/prettier-plugin-sort-imports to automatically sort imports in my React project. The sorting works for most cases, but I’m having issues getting .css and .scss imports that doesn’t start with ./ to always appear at the bottom of the list.

Here’s an example of my current imports:

import { PublicClientApplication } from '@azure/msal-browser';
import 'bootstrap/dist/css/bootstrap.min.css'; // this should be at the bottom
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';

import App from './App';
import { msalConfig } from './auth-config.ts';

import './styles/index.css';

And here’s my .prettierrc configuration:

{
  "printWidth": 80,
  "tabWidth": 2,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "es5",
  "bracketSpacing": true,
  "arrowParens": "always",
  "importOrder": ["^@?\w", "^@/", "^[./](?!.*\.(css|scss)$)", ".*\.(css|scss)$"],
  "importOrderSeparation": true,
  "importOrderSortSpecifiers": true,
  "plugins": ["@trivago/prettier-plugin-sort-imports"]
}

I expect the .css/.scss imports to always appear at the bottom of the import list, as specified by the .*\.(css|scss)$ rule. However, import 'bootstrap/dist/css/bootstrap.min.css'; is placed at the top of the list because it also matches the first rule (^@?\w).

Btw, this is the same reason why I excluded .css and .scss files from the ^[./](?!.*\.(css|scss)$) rule.

How do I fix this?

This is the same reason why I excluded .css/.scss from the 3rd rule "^[./](?!.*\.(css|scss)$)". How can I solve this?

my chrome extension for replacing all links to Youtube shorts from Youtube doesn’t work

it just like does absolutely nothing to my knowledge

here’s the manifest:

{
    "manifest_version":  3,
    "name": "NoScrollSorts",
    "version": "1.0.0",
    "content_scripts": [
    {
        "matches": ["http://www.youtube.com/*"],
        "js": ["nsyts.js"]
        
    }
    
]



}

here’s the script

lmf = document.getElementsByTagName("a");
for (bmf of lmf) {
    bmf.href = bmf.href.replace("shorts/","watch?v=");
    
}

How to use Node.js module on browser without using node server?

I want to use Google Gemini API to generate chat but don’t want to use node server. I want to use php apache server only. I can’t import using import { GenerativeModel, GoogleGenerativeAI } from "@google/generative-ai"; simply because it can’t trace the location.

Here is the code block for the reference:

import { GenerativeModel, GoogleGenerativeAI } from "@google/generative-ai";

$(document).ready(() => {
    const genAI = new GoogleGenerativeAI("");
    const model = genAI.getGenerativeModel({model: "gemini-1.5-flash", systemInstruction: "You are a competitive exam helper. Your name is Calculars."})
    let chat = model.startChat({
        history: [],
    })
});

I imported the file into my php file using script tag. Here is the error on browser’s console window.
Error on browser's console window

I want the module to be perfectly loaded and the chat to happen. I tried webpack but it messed up.

Website working fine on port 3000 but when i change it to 8080, the javascript does not work

I built a website that uses html, css and javascript. I have installed an extension named live preview by Microsoft, and when i preview my page, it uses port 3000 by default and the page works fine. But when I change the port number to 8080 from the settings, and then preview the page, the html and css of the page works fine but the javascript seems to be detached or not working. How do i solve this?

And for your information, the reason I am changing the port to 8080 is that i am not able to view the page on my phone using port 3000. It just keeps loading. When I change the port to 8080 and then type the ip-adress:8080, i can see the website but the javascript does not work.

Why does the draw:drawvertex event fire twice when drawing a Polygon in Leaflet Draw?

When using the Leaflet Draw plugin to draw a Polygon, the draw:drawvertex event fires twice for each vertex click. Is this the expected behavior, or is there an issue with my configuration or implementation?

I have also prepared a CodePen demo for reference (this behavior consistently occurs in my environment):

https://codepen.io/masushin/pen/QwLJrYv

To reproduce this issue, follow these steps:

  1. Select the Polygon drawing tool from the toolbar.
  2. Click on the map to create the vertices of a Polygon.

var map = L.map('map', {
  crs: L.CRS.Simple,
  minZoom: -3,
  maxZoom: 5,
  zoomControl: true,
  attributionControl: false
});

img = new Image();
img.src = "https://placehold.jp/150x150.png"
console.log('img.src', this.img.src);
this.img.onload = () => {
  let bounds = [[0, 0], [this.img.height, this.img.width]];
  L.imageOverlay(this.img, bounds).addTo(this.map);
  this.map.fitBounds(bounds);
};

var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
var drawControl = new L.Control.Draw({
  draw: {
    polygon: true,
    polyline: false,
    rectangle: false,
    circle: false,
    circlemarker: false,
    marker: false,
  },
  edit: {
    featureGroup: drawnItems
  }
});
map.addControl(drawControl);

map.on("draw:drawvertex", function (e) {
  console.log('draw:vertex', e);
});

map.on(L.Draw.Event.CREATED, function (e) {
  console.log(e)
  var type = e.layerType,
      layer = e.layer;
  if (type === 'polygon') {
    // Do marker specific actions
    console.log('polygon drawn');
    console.log(layer.toGeoJSON());
  }
  drawnItems.addLayer(e.layer);
});

For example, when drawing a rectangular polygon, I expect to get 5 vertices (including the closing vertex).
However, the resulting data includes 9 vertices instead.

I would like to understand:

Why the draw:drawvertex event fires twice for a single click.
If there are any necessary configurations or additional steps to resolve this issue.
I would greatly appreciate it if you could point out any mistakes or missing configurations in my code.

SVG filter to Pixi.js

Is it possible to create a filter in Pixi.js that performs exactly the same function as the following SVG filter:

<filter id="metaball">
  <feGaussianBlur in="SourceGraphic" stdDeviation="6" edgeMode="none" result="blur" />
  <feColorMatrix in="blur" result="blob" values="0 0 0 0 0, 0 0 0 0 0, 0 0 0 0 0, 0 0 0 8 -4" />
  <feMorphology in="blob" operator="dilate" radius="1" result="stroke" />
  <feComposite in="stroke" in2="blob" operator="out" result="result" />
</filter>

How to properly type the IdTokenData function component in TypeScript?

I’m trying to migrate the MSAL React SPA example to a TypeScript + React Vite project. While converting the DataDisplay.jsx file, I’m encountering typing issues.

Here’s the relevant code snippet from DataDisplay.tsx:

export const IdTokenData = (props: any) => {
  const tokenClaims = createClaimsTable(props.idTokenClaims);

  const tableRow = Object.keys(tokenClaims).map((key, index) => {
    return (
      <tr key={key}>
        {tokenClaims[key].map((claimItem) => (
          <td key={claimItem}>{claimItem}</td>
        ))}
      </tr>
    );
  });

Element implicitly has an ‘any’ type because index expression is not of type ‘number’.

Parameter ‘claimItem’ implicitly has an ‘any’ type.

The createClaimsTable function used above is defined in claimUtils.js. Here’s what it looks like:

export const createClaimsTable = (claims) => {
    let claimsObj = {};
    let index = 0;

    Object.keys(claims).forEach((key) => {
        if (typeof claims[key] !== 'string' && typeof claims[key] !== 'number') return;
        switch (key) {

        ...

What are the appropriate TypeScript types for:

  • The idTokenClaims prop in IdTokenData?
  • The createClaimsTable function’s parameter and return type?

How do I return the first object in a steam?

I have an event that fires calling another service which will create an organization. The organization is returned as an observable. I then use swithMap so I can get the organization id and use it to create an organization user. That response also returns an observable. In the subscribe next the data returned is not the organization, rather it is the organization user object. I want to return the organization, so I somehow need to get the first observable.

return new Promise((resolve, reject) => {
  this.organizationController
    .send(CREATE_ORGANIZATION, organizationEvent)
    .pipe(
      switchMap((org) => {
        if (org === null) {
          reject(new UnprocessableEntityException());
        }

        const organizationUserEvent: OrganizationUserEventDto = {
          dto: {
            userId: user.id,
            organizationId: org.id,
            role: Role.SUPER,
          },
        };

        return this.organizationController.send(
          CREATE_ORGANIZATION_USER,
          organizationUserEvent,
        );
      }),
    )
    .subscribe({
      next: (data) => {
        resolve(data);
      },
      error: (e) => {
        reject(e);
      },
    });
});

I tried many things and managed to get this to work with the following changes. As you can see I am simply mapping the second response and returning the data from the first observable instead. I feel like there must be a better way.

return new Promise((resolve, reject) => {
  this.organizationController
    .send(CREATE_ORGANIZATION, organizationEvent)
    .pipe(
      mergeMap((org) => {
        if (org === null) {
          reject(new UnprocessableEntityException());
        }

        const organizationUserEvent: OrganizationUserEventDto = {
          dto: {
            userId: user.id,
            organizationId: org.id,
            role: Role.SUPER,
          },
        };

        return this.organizationController
          .send(CREATE_ORGANIZATION_USER, organizationUserEvent)
          .pipe(
            map(() => {
              return { org: org };
            }),
          );
      }),
    )
    .subscribe({
      next: ({ org: org }) => {
        resolve(org);
      },
      error: (e) => {
        reject(e);
      },
    });
});

I also tried using wthLatestFrom with the below arrangment and this caused the first API call to occur twice and did not work.

return new Promise((resolve, reject) => {
  const $org = this.organizationController.send(
    CREATE_ORGANIZATION,
    organizationEvent,
  );

  $org
    .pipe(
      mergeMap((org) =>
        this.organizationController.send(CREATE_ORGANIZATION_USER, {
          userId: user.id,
          organizationId: org.id,
          role: Role.SUPER,
        }),
      ),
      withLatestFrom($org),
    )
    .subscribe({
      next: ([data, org]) => {
        resolve(data);
      },
      error: (e) => {
        reject(e);
      },
    });
});

I appreciate any input. Thank you in advance.

What are the cons of using Frappe Framework and why not to use for large scaling software apps [closed]

I’m evaluating the Frappe Framework for software development and have a few concerns:

  1. What are the main issues or limitations of using the Frappe Framework, particularly for large-scale applications?

  2. Are there any future concerns regarding its adoption or career prospects in this ecosystem?

  3. Should freshers start with Frappe, or would it be better to focus on newer, trending technologies?

Looking for insights to make an informed decision.

Alpine Expression Error: cards is not defined

I have this views/Home.html:

<div x-data="cards">
  <h2>Bienvenue sur SwiftDeli !</h2>
  <p>
    Commencez à créer et partager des recettes, ingrédients et listes de
    courses.
  </p>

  <div class="grid">
    <template x-for="card in cards" :key="card.url">
      <a :href="card.url" class="clickable-card">
        <h3 x-text="card.title"></h3>
        <p x-text="card.description"></p>
      </a>
    </template>
  </div>
</div>

And this views/Home.js:

import template from "./Home.html?raw";
console.log("HTML Home View Loaded");

// Define the cards array
const cards = [
  {
    url: "/create-recipe",
    title: "Ajouter une recette",
    description: "Cliquez pour créer une nouvelle recette.",
  },
  {
    url: "/recipes",
    title: "Consulter les recettes",
    description: "Cliquez pour voir toutes les recettes.",
  },
  {
    url: "/groceries",
    title: "Aller aux courses",
    description: "Cliquez pour voir votre liste de courses.",
  },
];

// Register the cards component with Alpine.js
document.addEventListener("alpine:init", () => {
  console.log("Alpine.js initialized");
  Alpine.data("cards", () => ({
    cards: cards,
  }));
});

// Initialize the component
export default () => ({
  init() {
    console.log("Home View Loaded");

    // Inject the template into the DOM
    const contentElement = document.getElementById("content");
    contentElement.innerHTML = template;

    // Initialize Alpine.js on the new content
    Alpine.initTree(contentElement);
    console.log("Alpine.js initialized on new content");
  },
});

I use Vite, which seem to work fine and here is my main.js:

import Alpine from "alpinejs";
import Navigo from "navigo";

// Initialize Alpine.js
window.Alpine = Alpine;
Alpine.start();

// Initialize Navigo router
const router = new Navigo("/");

// Define views (dynamically loaded)
const views = {
  home: () => import("./views/Home.js")
};

// Router setup
router.on({
  "/": async () => {
    const { default: Home } = await views.home();
    const homeView = Home();
    homeView.init();
  },
  "*": () => {
    document.getElementById("content").innerHTML = "<h2>Page non trouvée</h2>";
  },
});

router.resolve();

When loading the home page I get Alpine Expression Error: cards is not defined. I have the feeling the cards variable is not passed to the HTML, but I wonder how to check that, and resolve this issue. I can see my layout just fine, just without the cards.

md5 in python and javascript are not the same

I have in JavaScript a var (vardata) with only chars [0-9a-f-] and generate with this line a hash:

hash = crypto
        .createHash('md5')
        .update('*salt* ' + (new Date().toISOString().substr(0, 13)) + vardata)
        .digest('hex');

In Python I’m use this line:

hash = hashlib
        .md5(('*salt* ' + datetime.datetime.now().isoformat()[0:13] + vardata).encode('utf-8'))
        .hexdigest()

Both hashes are not the same?!?!

What is wrong?

How can I fix the Uncaught runtime errors?

I get

Uncaught runtime errors:
×
ERROR
Script error.
handleError@http://localhost:3000/static/js/bundle.js:106227:67
@http://localhost:3000/static/js/bundle.js:106246:18

errors when I try to add stripe to my code. I couldn’t fix it for like hours. This is my code down below:

import React from "react";
import { loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js";
import OrderCartPayment from "./OrderCartPayment";


const stripePromise = loadStripe(
  process.env.REACT_APP_STRIPE_PUBLISHABLE_KEY ||
    "my_stripe_pk"
);


stripePromise.catch((error) => {
  console.error("Stripe initialization error:", error);
});

const PaymentPageWrapper: React.FC = () => {
  try {
    return (
      <Elements stripe={stripePromise}>
        <OrderCartPayment />
      </Elements>
    );
  } catch (error) {
    console.error("Error rendering payment page:", error);
    return <p>Failed to load the payment page. Please try again later.</p>;
  }
};

export default PaymentPageWrapper;

I have been trying multiple codes but they don’t work at all. It all comes to the same end.