Smooth Mouse Action Implementation in React using GSAP

I’m trying to implement smooth scrolling action using GSAP in react. Note that this is different from usual smooth scrolling. An example of what I’m trying to replicate can be seen in this website:

This is my attempt:

import React, { useRef, useEffect, useState } from 'react';
import { TweenLite } from 'gsap';

const Scroller = () => {
  const [scroller, setScroller] = useState({
    target: null,
    ease: 0.05,
    endY: 0,
    y: 0,
    resizeRequest: 1,
    scrollRequest: 0,
  });

  const requestRef = useRef(null);

  const onLoad = () => {
    updateScroller();
    window.focus();
    window.addEventListener("resize", onResize);
    document.addEventListener("scroll", onScroll);
  };

  const updateScroller = () => {
    const resized = scroller.resizeRequest > 0;

    if (resized) {
      const height = scroller.target.clientHeight;
      document.body.style.height = height + "px";
      setScroller(prevState => ({
        ...prevState,
        resizeRequest: 0,
      }));
    }

    const scrollY = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

    setScroller(prevState => ({
      ...prevState,
      endY: scrollY,
      y: prevState.y + (scrollY - prevState.y) * prevState.ease,
    }));

    if (Math.abs(scrollY - scroller.y) < 0.05 || resized) {
      setScroller(prevState => ({
        ...prevState,
        y: scrollY,
        scrollRequest: 0,
      }));
    }

    TweenLite.set(scroller.target, {
      y: -scroller.y,
    });

    requestRef.current = scroller.scrollRequest > 0 ? requestAnimationFrame(updateScroller) : null;
  };

  const onScroll = () => {
    setScroller(prevState => ({
      ...prevState,
      scrollRequest: prevState.scrollRequest + 1,
    }));

    if (!requestRef.current) {
      requestRef.current = requestAnimationFrame(updateScroller);
    }
  };

  const onResize = () => {
    setScroller(prevState => ({
      ...prevState,
      resizeRequest: prevState.resizeRequest + 1,
    }));

    if (!requestRef.current) {
      requestRef.current = requestAnimationFrame(updateScroller);
    }
  };

  useEffect(() => {
    setScroller(prevState => ({
      ...prevState,
      target: document.querySelector("#scroll-container"),
    }));
  }, []);

  useEffect(() => {
    if (scroller.target) {
      TweenLite.set(scroller.target, {
        rotation: 0.01,
        force3D: true,
      });
    }
  }, [scroller.target]);

  useEffect(() => {
    window.addEventListener('load', onLoad);
    return () => {
      window.removeEventListener('load', onLoad);
      window.removeEventListener('resize', onResize);
      document.removeEventListener('scroll', onScroll);
      cancelAnimationFrame(requestRef.current);
    };
  }, []);

  return (
    <section className="viewport">
      <div id="scroll-container" className="scroll-container">
        <div className="content">

          <div className="img-container">
            <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/106114/splash-10.jpg" alt="" />
          </div>
          <div className="img-container">
            <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/106114/splash-14.jpg" alt="" />
          </div>
          <div className="img-container">
            <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/106114/splash-15.jpg" alt="" />
          </div>
          <div className="img-container">
            <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/106114/splash-16.jpg" alt="" />
          </div>

          {/* Repeat the images section as needed */}

        </div>
      </div>
    </section>
  );
};

export default Scroller;

However, this is not working. There is no error whatsoever, but there is no difference in the scrolling action either.

Please help me out, thanks in advance!

FFMPEG node.js using with ytdl

I have nodejs javascript code and I want that the video and the audio is downloaded, to combine it with ffmpeg. First, the video is longer that it should be, idk why. Second, the ffmpeg is not working because I’m getting an error, that ffmpeg can’t find (but I installed fluent-ffmpeg via npm correctly)

My code:

const fs = require('fs');
const ytdl = require('ytdl-core');
const ffmpeg = require('fluent-ffmpeg');



// Function to download the youtube video
function download() {
    const linkInput = document.getElementById('linkInp');
    const resolution = document.getElementById('resolution');
    const videoTitle = document.getElementById('videoTitle');
    const videoAuthor = document.getElementById('videoAuthor');
    const videoUploadDate = document.getElementById('videoUploadDate');
    const videoPicture = document.getElementById('videoPic');
    const link = linkInput.value;
    console.log('Downloading following video from link: ', link, ' with resolution id: ', resolution.value);

    ytdl.getInfo(link).then((info) => {
        const format = ytdl.chooseFormat(info.formats, { quality: `${resolution.value}` });
        const videoFilePath = `${info.videoDetails.title}.${format.container}`;
        const audioFilePath = `${info.videoDetails.title}.mp3`;

        // before download, collect meta datas
        videoTitle.innerHTML = info.videoDetails.title;
        videoAuthor.innerHTML = info.videoDetails.author.name;
        videoUploadDate.innerHTML = info.videoDetails.uploadDate;
        videoPicture.src = info.videoDetails.thumbnails[0].url;

        // start downloading the video
        ytdl.downloadFromInfo(info, { format: format }).pipe(fs.createWriteStream(videoFilePath));

        // download audio separately
        ytdl.downloadFromInfo(info, { filter: 'audioonly' }).pipe(fs.createWriteStream(audioFilePath)).on('finish', () => {
            // merge video and audio after both are downloaded
            ffmpeg()
                .input(videoFilePath)
                .input(audioFilePath)
                .videoCodec('copy')
                .audioCodec('copy')
                .save(`${info.videoDetails.title}_with_audio.${format.container}`)
                .on('end', () => {
                    console.log('Video with audio merged successfully!');
                    fs.unlink(videoFilePath, (err) => {
                        if (err) console.error(err);
                    });
                    fs.unlink(audioFilePath, (err) => {
                        if (err) console.error(err);
                    });
                });
        });

    }).catch((err) => {
        console.error(err);
        document.getElementById('msg').style.display = 'block';
        document.getElementById('message').innerHTML = err;
    });
}

Thanks for every help!

Change dark mode using main.js electron

Building a simple electron application following a beginners tutorial and trying to control dark mode appearance through a menu checkbox using the main process.

const template = [{
  label: 'Préférences',
  submenu: [{
      label: 'Mode nuit',
      id: 'mode',
      type: 'checkbox',
      click: () => function(menuItem) {
        if (menuItem.checked) {
          mainWindow.setBackgroundColor('black');
          mainWindow.setColor('white');
        } else {
          mainWindow.setBackgroundColor('white');
          mainWindow.setColor('black');
        }
      }
    },
    {
      type: 'separator'
    },
    {
      label: 'Police',
      submenu: [{
          label: 'Petit',
          type: 'radio'
        },
        {
          label: 'Moyen',
          type: 'radio'
        },
        {
          label: 'Grand',
          type: 'radio'
        }

      ]
    }
  ]
}];

It is not working. Is it possible to do it this way or should I modify the renderer process?

How to make the bootstrap next and prev buttons in the carousel work?

Recently got interested on bootstrap 5 for my website design. I decided to add a carousel for my coffee items that will show only 3 products at same time when the right and left arrow buttons are clicked.

My current html container class is showing 3 items but when I press the buttons it doesn’t move and show my 4th item. I kind of want it to show the 4th item when i press the left and right or next and prev button while maintaining 3 items shown in the carousel

Here is my carousel html block:

<div class="container mt-5">
      <div class="carousel-container">
          <div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel">
              <div class="carousel-inner">
                  <div class="carousel-item active">
                      <h1 class="text-white fw-bold mb-3 mt-3" style="text-align: center;">Popular Now</h1>
                      <div class="d-flex justify-content-center align-items-center">
                          <!-- First carousel item -->
                          <div class="product-item">
                              <div class="product-info bg-dark text-light p-3">
                                  <div class="product-image" style="background-image: url('/image/latte.jpg');"></div>
                                  <div class="product-text">
                                      <h5 class="mb-3">Latte Art Coffee</h5>
                                      <p class="mb-2">With Milk</p>
                                      <p class="mb-0 price-container">
                                        ₱ 60<span class="price-space"></span><button class="plus-btn">+</button>
                                      </p>
                                  </div>
                              </div>
                          </div>
                          <!-- Second carousel item -->
                          <div class="product-item">
                              <div class="product-info bg-dark text-light p-3">
                                  <div class="product-image" style="background-image: url('/image/espresso.jpg');"></div>
                                  <div class="product-text">
                                      <h5 class="mb-3">Espresso Coffee</h5>
                                      <p class="mb-2">With Milk</p>
                                      <p class="mb-0">₱ 70<span class="price-space"></span><button class="plus-btn">+</button></p>
                                  </div>
                              </div>
                          </div>
                          <!-- Third carousel item -->
                          <div class="product-item">
                              <div class="product-info bg-dark text-light p-3">
                                  <div class="product-image" style="background-image: url('/image/mocha.jpg');"></div>
                                  <div class="product-text">
                                      <h5 class="mb-3">Mocha Coffee</h5>
                                      <p class="mb-2">With Chocolate</p>
                                      <p class="mb-0">₱ 80 <span class="price-space"></span><button class="plus-btn">+</button></p>
                                  </div>
                              </div>
                          </div>
                          <!-- Fourth carousel item (hidden initially) -->
                          <div class="product-item d-none">
                              <div class="product-info bg-dark text-light p-3">
                                  <div class="product-image" style="background-image: url('/image/affogato.jpg');"></div>
                                  <div class="product-text">
                                      <h5 class="mb-3">Affogato</h5>
                                      <p class="mb-2">With Milk</p>
                                      <p class="mb-0">₱ 90 <span class="price-space"></span> <button class="plus-btn">+</button></p>
                                  </div>
                              </div>
                          </div>
                          <!-- End carousel items -->
                      </div>
                  </div>
              </div>
              <div class="carousel-controls-container">
                <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
                  <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                  <span class="visually-hidden">Previous</span>
                </button>
                <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
                  <span class="carousel-control-next-icon" aria-hidden="true"></span>
                  <span class="visually-hidden">Next</span>
                </button>
              </div>
          </div>
      </div>

my bootstrap link:

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

my bootstrap script:

 <script src="js/script.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">
</script>

I tried adding a JavaScript function but still I get the same result:

/js/script.js

// Initialize the Bootstrap Carousel component without waiting for the entire document to load
var myCarousel = document.querySelector('#carouselExampleControls');
var carousel = new bootstrap.Carousel(myCarousel, {
  interval: false, // Disable automatic sliding
  wrap: false // Disable looping of carousel items
});

// Show/hide the fourth carousel item based on slide events
myCarousel.addEventListener('slide.bs.carousel', function (event) {
  var slideFrom = event.detail.from;
  var slideTo = event.detail.to;
  var items = myCarousel.querySelectorAll('.carousel-item');

  // Hide the fourth item if sliding from the first item
  if (slideFrom === 0) {
    items[3].classList.add('d-none');
  }
  // Show the fourth item if sliding to the first item
  if (slideTo === 0) {
    items[3].classList.remove('d-none');
  }
});

script in my html:

<script src="js/script.js"></script>

this is the 4th item i want to show when the arrows are clicked left or right:

<!-- Fourth carousel item (hidden initially) -->
                          <div class="product-item d-none">
                              <div class="product-info bg-dark text-light p-3">
                                  <div class="product-image" style="background-image: url('/image/affogato.jpg');"></div>
                                  <div class="product-text">
                                      <h5 class="mb-3">Affogato</h5>
                                      <p class="mb-2">With Milk</p>
                                      <p class="mb-0">₱ 90 <span class="price-space"></span> <button class="plus-btn">+</button></p>
                                  </div>
                              </div>
                          </div>

Vite SSR React SEO not rendering on Vercel server but on local machine

So I have been struggling to get setting up my vite SSR react server right so it can render my react-helmet-async meta tags.
Worked my way on getting it to render the meta tags and links with this entry-server.jsx snippet:

import React from "react";
import ReactDOMServer from "react-dom/server";
import App from "./components/App";
import { StaticRouter } from "react-router-dom/server";
import { Router, helmetContext } from "./routes/Routes";
import { Helmet } from "react-helmet-async";

export function render({ path }) {
  const html = ReactDOMServer.renderToString(
    <StaticRouter location={path}>
      <Router />
    </StaticRouter>
  );

  const { helmet } = helmetContext;
  const head = `
  ${helmet.title.toString()} 
  ${helmet.priority.toString()} 
  ${helmet.meta.toString()} 
  ${helmet.link.toString()} 
  ${helmet.script.toString()}
  `;
  return { html, head };
}

Which worked out with this snippet on the server.js:

    let template;
    let render;
    if (!isProduction) {
      // Always read fresh template in development
      template = await fs.readFile("./index.html", "utf-8");
      template = await vite.transformIndexHtml(url, template);
      render = (await vite.ssrLoadModule("/src/entry-server.jsx")).render;
    } else {
      template = templateHtml;
      render = (await import("./dist/server/entry-server.js")).render;
    }

    const rendered = await render(url, ssrManifest);

    const html = template
      .replace(`<!--app-head-->`, rendered.head ?? "")
      .replace(`<!--app-html-->`, rendered.html ?? "");

It works on my local machine, don’t get me wrong. It renders the server side when I build and preview; I know this by viewings the source code on my Google Chrome browser – not via inspect or dev mode.

But now, when I deploy my app to Vercel for some reason the SEO doesn’t get recognised by crawlers and when I view the source code, the meta tags and html doesn’t get injected, therefore it only gets rendered on the client side.

I have a feeling that this might be an error on the Vercel server but I can’t be sure about that.

I want to understand how I could go about it.

Here is the project repo:
https://github.com/unnamed-lab/fullmoon-real-estate

Not found js files in project (NextJs and ReactJs)

I ran into a problem importing js files (these are libraries). I am using NextJS 14.1.3 and ReactJS 18.2.0.

Here is the path to these files
Here is the path to these files

Project structure
Project structure

This is the way I imported the files

import Script from 'next/script';

render() {
        const {Component, pageProps}: any = this.props;

        // During SSR, this will create new store instances so having `initialData` is crucial.
        // During the client-side hydration, same applies.
        // From then on, calls to `getStores()` return existing instances.
        const stores = getStores();

        return (
            <StoreProvider value={stores}>
                <Script
                    src='/public/js/LunaPass.1.6.8.js'
                    strategy="beforeInteractive"
                />
                <Script
                    src='/public/js/LPMessageRenderer.1.6.8.js'
                    strategy="beforeInteractive"
                />
                <Component {...pageProps} />
            </StoreProvider>
        );
    }

Error itself
Error in console

Has anyone encountered such a problem?

My expectation of my actions is to import js files and then use them in other pages.

MarkMap Toolbar renders but doesn’t attach to the embedded script

I have a simple static HTML page using MarkMap. I link to two required libraries to enable the functionality. I don’t quite know why I can render the mindmap AND the default Toolbar, but no clicks on the toolbar perform the corresponding actions (e.g., Zoom In, Zoom Out, Recenter, etc.). Any help is greatly appreciated.

Code and Stackblitz link follow:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Markmap</title>
    <style>
      svg.markmap {
        width: 100%;
        height: 100vh;
      }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
  </head>
  <body>
    <div id="container">
      <div id="mm" class="markmap">
        <script type="text/template">
          ---
          markmap:
            maxWidth: 300
            colorFreezeLevel: 2
          ---

          # markmap

          ## Links

          - <https://markmap.js.org/>
          - [GitHub](https://github.com/markmap/markmap)

          ## Related

          - [coc-markmap](https://github.com/markmap/coc-markmap)
          - [gatsby-remark-markmap](https://github.com/markmap/gatsby-remark-markmap)

          ## Features
          - links
          - **inline** ~~text~~ *styles*
          - multiline
            text
          - `inline code`
          - Katex - $x = {-b pm sqrt{b^2-4ac} over 2a}$
          - This is a very very very very very very very very very very very very very very very long line.
        </script>
        <script>
          const { markmap } = window;
          const { Toolbar } = markmap;

          const { el } = Toolbar.create(mm);
          el.style.position = 'absolute';
          el.style.bottom = '0.5rem';
          el.style.right = '0.5rem';

          // `container` could be the element that contains both the markmap and the toolbar
          container.append(el);
        </script>
      </div>
    </div>
  </body>
</html>

StackBlitz working demo here

‘404 not found’ error showing on vercel deployment

Guys seems like there is an issues while deploying my web audio player app to vercel

The project is located here –
https://github.com/blazeinferno64/blaze-audio-player

I didn’t used any frameworks instead I just used plain HTML CSS and JavaScript code to make my web app

Also there isn’t any custom backend

Can someone help me?

I tried adding vercel.json file but it didn’t seem to work!

Save a JSON array into one text record per array element

I have an application which, from time to time, saves JSON arrays into text files. All the elements of the JSON array display identical structure.

As an example, consider the following JSON array:

[{"A":1,"B":2},{"A":11,"B":22},{"A":111,"B":222}]

The need is to save this into a file such that it would look like this:

[{"A":1,"B":2} , 
{"A":11,"B":22} , 
{"A":111,"B":222}]

meaning, one record within the text file for each JSON element in the array.

The reason for that is that those JSON arrays may include hundreds and up to several thousands of elements and I wish to keep these files READABLE for humans.

Is there any trick that can be invoked when using the standard JSON.stringify method? If not, any other suggestion will be appreciated.

The entire column of cards expands with one click

I created the cards of this tab using loop and the data is coming from database.
when I click on show more button the entire visible column expands with it.
it does not show the content of just expands, the content are visible when I click show more.
but if its one card in on line its just expands that only

import React, { useState } from "react";
import {
  Box,
  Card,
  CardActions,
  CardContent,
  Collapse,
  Button,
  Typography,
  Rating,
  useTheme,
  useMediaQuery,
} from "@mui/material";
import Header from "../../components/Header";
import { useGetProductsQuery } from "../../state/api";
import LinearProgress from "@mui/material/LinearProgress";

const Product = ({
  _id,
  name,
  description,
  price,
  rating,
  category,
  supply,
  stat,
}) => {
  const theme = useTheme();
  const [isExpanded, setIsExpanded] = useState(false);

  return (
    <Card
      sx={{
        backgroundImage: "none",
        backgroundColor: theme.palette.background.alt,
        borderRadius: "0.55rem",
      }}
    >
      <CardContent>
        <Typography
          sx={{ fontSize: 14 }}
          color={theme.palette.secondary[700]}
          gutterBottom
        >
          {category}
        </Typography>
        <Typography variant="h5" component="div">
          {name}
        </Typography>
        <Typography sx={{ mb: "1.5rem" }} color={theme.palette.secondary[400]}>
          ${Number(price).toFixed(2)}
        </Typography>
        <Rating value={rating} readOnly />

        <Typography variant="body2">{description}</Typography>
      </CardContent>
      <CardActions>
        <Button
          variant="primary"
          size="small"
          onClick={() => setIsExpanded(!isExpanded)}
          sx={{ backgroundColor: theme.palette.secondary[600] }}
        >
          See More
        </Button>
      </CardActions>
      <Collapse
        in={isExpanded}
        timeout="auto"
        unmountOnExit
        sx={{
          color: theme.palette.neutral[300],
        }}
      >
        <CardContent>
          <Typography>id: {_id}</Typography>
          <Typography>Supply Left: {supply}</Typography>
          <Typography>
            Yearly Sales This Year: {stat[0].yearlySalesTotal}
          </Typography>
          <Typography>
            Yearly Units Sold This Year: {stat[0].yearlyTotalSoldUnits}
          </Typography>
        </CardContent>
      </Collapse>
    </Card>
  );
};

const Products = () => {
  const { data, isLoading } = useGetProductsQuery();
  const isNonMobile = useMediaQuery("(min-width: 1000px)");

  return (
    <Box m="1.5rem 2.5rem">
      <Header title="PRODUCTS" subtitle="See your list of products." />
      {data || !isLoading ? (
        <Box
          mt="20px"
          display="grid"
          gridTemplateColumns="repeat(4, minmax(0, 1fr))"
          justifyContent="space-between"
          rowGap="20px"
          columnGap="1.33%"
          sx={{
            "& > div": { gridColumn: isNonMobile ? undefined : "span 4" },
          }}
        >
          {data.map(
            ({
              _id,
              name,
              description,
              price,
              rating,
              category,
              supply,
              stat,
            }) => (
              <Product
                key={_id}
                _id={_id}
                name={name}
                description={description}
                price={price}
                rating={rating}
                category={category}
                supply={supply}
                stat={stat}
              />
            )
          )}
        </Box>
      ) : (
        <>
          <LinearProgress
            color="primary"
            fourcolor="false"
            variant="indeterminate"
          />
        </>
      )}
    </Box>
  );
};

export default Products;```
[this is the image of cards(https://i.stack.imgur.com/Ur2m8.png)


well I expect it to expands only one card at a time

next js routing issue

import { useCallback, useMemo, useState, useEffect } from 'react';
import Head from 'next/head';
import ArrowDownOnSquareIcon from '@heroicons/react/24/solid/ArrowDownOnSquareIcon';
import ArrowUpOnSquareIcon from '@heroicons/react/24/solid/ArrowUpOnSquareIcon';
import PlusIcon from '@heroicons/react/24/solid/PlusIcon';
import { Box, Button, Container, Stack, SvgIcon, Typography } from '@mui/material';
import { useSelection } from 'src/hooks/use-selection';
import { Layout as DashboardLayout } from 'src/layouts/dashboard/layout';
import { applyPagination } from 'src/utils/apply-pagination';
import { Modal, Backdrop, Fade, TextField } from '@mui/material';
import AddProductModal from 'src/components/AddProductModal';
import AddItemsModal from 'src/components/AddItemModal';
import { useDispatch, useSelector } from 'react-redux';
import { getAllProducts } from 'src/redux/productSlice';
import AddCategoryModal from 'src/components/AddCategoryModal';
import { MaterialReactTable, useMaterialReactTable } from 'material-react-table';
import { getAllCategories } from 'src/redux/categorySlice';
import { formatDistanceToNow } from 'date-fns';
import { parseISO } from 'date-fns';
import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper } from '@mui/material';



const useCategories = () => {
  const categoriesState = useSelector((state) => state.category.categories);
  const { user } = useSelector((state) => state.auth);

  return useMemo(() => {
    if (user.isVendor) {
      const filteredCategories = categoriesState.filter((category) =>
        category.item._id === user.vendorDetails.item
      );
      return filteredCategories;
    }

    return categoriesState;
  }, [categoriesState, user, user]);
};


const useCategoryIds = (categories) => {
  return useMemo(() => {
    if (categories) {
      return categories.map((category) => category._id);
    }
    return [];
  }, [categories]);
};

const renderDetailPanel = ({ row }) => {
  const products = row.original.products;
  if (!products || products.length === 0) {
    return null;
  }

  return (
    <TableContainer component={Paper}>
      <Table size="small" aria-label="a dense table">
        <TableHead>
          <TableRow>
            <TableCell>Product Name</TableCell>
            <TableCell align="right">Location</TableCell>
            <TableCell align="right">Price</TableCell>
            <TableCell align="right">Dimension</TableCell>
            <TableCell align="right">Unit</TableCell>
            <TableCell align="right">Created At</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {products.map((product) => (
            <TableRow key={product._id}>
              <TableCell component="th" scope="row">
                {product.name}
              </TableCell>
              <TableCell align="right">{product.location}</TableCell>
              <TableCell align="right">{product.price}</TableCell>
              <TableCell align="right">{product.dimension}</TableCell>
              <TableCell align="right">{product.unit}</TableCell>
              <TableCell align="right">
                {formatDistanceToNow(parseISO(product.createdAt), { addSuffix: true })}
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
};


const ProductsPage = () => {
  const dispatch = useDispatch();
  const { user } = useSelector((state) => state.auth);
  const { categoryStatus } = useSelection((state) => state.category)

  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(5);
  const categories = useCategories(page, rowsPerPage);
  const categoryIds = useCategoryIds(categories);
  const categoriesSelection = useSelection(categoryIds);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isAddProductModalOpen, setIsAddProductModalOpen] = useState(false);
  const [isAddItemsModalOpen, setIsAddItemsModalOpen] = useState(false);
  const [isAddCategoryModalOpen, setIsAddCategoryModalOpen] = useState(false);

  useEffect(() => {
    dispatch(getAllCategories());
  }, [dispatch, isModalOpen]);

  const handlePageChange = useCallback(
    (event, value) => {
      setPage(value);
    },
    []
  );

  const handleRowsPerPageChange = useCallback(
    (event) => {
      setRowsPerPage(event.target.value);
    },
    []
  );

  const handleOpenModal = () => {
    setIsModalOpen(true);
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
  };

  const handleOpenAddProductModal = () => {
    setIsAddProductModalOpen(true);
  };

  const handleCloseAddProductModal = () => {
    setIsAddProductModalOpen(false);
  };

  const handleOpenAddItemsModal = () => {
    setIsAddItemsModalOpen(true);
  };

  const handleCloseAddItemsModal = () => {
    setIsAddItemsModalOpen(false);
  };

  const handleOpenAddCategoryModal = () => {
    setIsAddCategoryModalOpen(true);
  };

  const handleCloseAddCategoryModal = () => {
    setIsAddCategoryModalOpen(false);
  };

  const columns = useMemo(
    () => [
      {
        accessorKey: 'item.img',
        header: 'Image',
        Cell: ({ row }) => (
          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              gap: '1rem',
            }}
          >
            <img
              alt="avatar"
              height={50}
              src={row.original.item.img}
              loading="lazy"
              style={{ borderRadius: '50%' }}
            />
            {/* using renderedCellValue instead of cell.getValue() preserves filter match highlighting */}
          </Box>
        ),

      },
      {
        accessorKey: 'item.name',
        header: 'Category Item',
        size: 200,
      },

      {
        accessorKey: 'name',
        header: 'Category Name',
        size: 200,
      },
      {
        accessorKey: 'unit',
        header: 'Unit',
        size: 150,
      },
      {
        accessorKey: 'createdAt',
        header: 'Created At',
        size: 150,
        Cell: ({ row }) => {
          const formattedDate = formatDistanceToNow(parseISO(row.original.createdAt), { addSuffix: true });
          return <span>{formattedDate}</span>;
        },
      },
    ],
    [],
  );

  const table = useMaterialReactTable({
    columns,
    data: categories,
    renderDetailPanel,
  });


  return (
    <>
      <Head>
        <title>Categories | Your App Name</title>
      </Head>
      <Box
        component="main"
        sx={{
          flexGrow: 1,
          py: 8,
        }}
      >
        <Container maxWidth="xl">
          <Stack spacing={3}>
            <Stack
              direction="row"
              justifyContent="space-between"
              spacing={4}
            >
              <Stack spacing={1} direction="row">
                <Typography variant="h4">Product/Categories</Typography>
                <Stack
                  alignItems="center"
                  direction="row"
                  spacing={1}
                >

                </Stack>
              </Stack>
              <Stack spacing={1} direction="row">
                <Button
                  startIcon={(
                    <SvgIcon fontSize="small">
                      <PlusIcon />
                    </SvgIcon>
                  )}
                  variant="contained"
                  onClick={handleOpenAddProductModal}
                >
                  Add Product
                </Button>
                <AddProductModal isOpen={isAddProductModalOpen} onClose={handleCloseAddProductModal} />

                {!user.isVendor && (<Button
                  startIcon={(
                    <SvgIcon fontSize="small">
                      <PlusIcon />
                    </SvgIcon>
                  )}
                  variant="contained"
                  onClick={handleOpenAddItemsModal}
                >
                  Add Items
                </Button>)}


                <AddItemsModal isOpen={isAddItemsModalOpen} onClose={handleCloseAddItemsModal} />

                {!user.isVendor && (<Button
                  startIcon={(
                    <SvgIcon fontSize="small">
                      <PlusIcon />
                    </SvgIcon>
                  )}
                  variant="contained"
                  onClick={handleOpenAddCategoryModal}
                >
                  Add Categories
                </Button>)}

                <AddCategoryModal isOpen={isAddCategoryModalOpen} onClose={handleCloseAddCategoryModal} />
              </Stack>
            </Stack>
            {categories && Array.isArray(categories) && categories.length > 0 && <MaterialReactTable table={table} />}
          </Stack>
        </Container>
      </Box>
    </>
  );
};

ProductsPage.getLayout = (page) => (
  <DashboardLayout>
    {page}
  </DashboardLayout>
);

export default ProductsPage;

this is above my products page in next js ,and there are other pages too like orders,

the issue is all pages routing are working fine but when i go to product page and then i click to another page from sidenav link after coming to product page,the page doesnt change no error in console rest all pages are working productis also working fine only page are not getting routed after going to product page

Trouble Deleting Items from Cart Using AJAX In Django

I am new in Stack overflow
and I am getting problem during deleting product from cart
In my cart.html:

<button class="btn btn-sm btn-remove delete-item" data-item="{{product_id}}"><i class="fas fa-trash-alt" ></i></button>

This is the delete button I created. Now also I created js for this button
so in my cart.js:

console.log("Hi");

$(document).on("click", '.delete-item' ,function(){
    let this_val=$(this)
    var _pID=$(this).attr('data-item');
    console.log(_pID);

    $.ajax({
        url: '/delete-from-cart',
        data: {
            'id': _pID,
        },
        dataType: 'json',
        beforeSend: function(){
            this_val.hide()
        },
        success: function(response){
            this_val.show()
            $(".cart-items-count").text(response.totalcartitems)
            $("#cart-list").html(response.data)
        }
    })
})

for the js file when i am clicking on the delete button I am getting product ids as output
I also created a views for it. So, In my views.py:

def delete_item_from_cart(request):
    product_id=str(request.GET['id'])
    if 'cart_data_obj' in request.session:
        if product_id in request.session['cart_data_obj']:
            cart_data=request.session['cart_data_obj']
            del request.session['cart_data_obj'][product_id]
            request.session['cart_data_obj'] = cart_data

    cart_total_ammount=0
    if 'cart_data_obj' in request.session:
        for p_id, item in request.session['cart_data_obj'].items():
             cart_total_ammount += int(item['qty']) * float(item['price'])

    context= render_to_string("core/async/cart_list.html", {"products":products}, {"data":request.session['cart_data_obj'],'totalcartitems': request.session['total_cart_items'] ,'cart_total_ammount':cart_total_ammount})
    return JsonResponse({"data": context, 'totalcartitems': request.session['total_cart_items'] ,'cart_total_ammount':cart_total_ammount})

and then In urls.py:

path("delete-from-cart/", delete_item_from_cart,name="delete-from-cart"),

this is my url

Note: At last I would say that I made a cart page where all the products are displaying which are sellected. and I connected cart-lsit.html with cart.html by main tag with id

you can see this in the below code
in cart.html:

{% extends 'partials/base.html'%}


{%load static%}

{% block content %}
    <main class="main" id="cart-list">
        <div class="container1">
            <center><h2 style="font-size: 28px; color: #FFC0CB; font-weight: bold;">Your Shopping Cart</h2></center>
            <div class="row">
                {% for product_id, item in data.items %}
                <div class="col-md-8">
                    <div class="cart-item">
                        <div class="row">
                            <div class="col-md-2">
                                <a href="{%  url 'core:product_detail' item.pid  %}">
                                    <img src="{{item.image}}" alt="Product Image" class="product-image">
                                </a>
                            </div>
                            <div class="col-md-6 product-details">
                                <a href="{%  url 'core:product_detail' item.pid  %}">
                                    <h4>{{item.title}}</h4>
                                </a>
                                <p>Product description lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
                                <div class="quantity-control">
                                    <button class="btn btn-sm btn-update"><i class="fas fa-sync-alt"></i></button>
                                    <input type="number" class="form-control quantity-input" value="{{item.qty}}">
                                    <button class="btn btn-sm btn-remove delete-item" data-item="{{product_id}}"><i class="fas fa-trash-alt" ></i></button>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <h4>{{item.price}}/Quantity</h4>
                            </div>
                        </div>
                    </div>
                    <!-- More cart items can be added dynamically here -->
                </div>
                {%  endfor  %}
                <div class="col-md-4">
                    <div class="cart-item total-section">
                        <h3>Total: <span class="total">{{cart_total_ammount}}</span></h3>
                        <button class="btn btn-checkout">Proceed to Checkout</button>
                    </div>
                </div>
            </div>
        </div>
        <script src="{% static 'assets/js/cart.js' %}"></script>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    </main>
    </body>
{%  endblock content  %}

The same main id of the above code i am using for cart-list.html:

<body>
    <main class="main" id="cart-list">
        <div class="container1">
            <center><h2 style="font-size: 28px; color: #FFC0CB; font-weight: bold;">Your Shopping Cart</h2></center>
            <div class="row">
                {% for product_id, item in data.items %}
                <div class="col-md-8">
                    <div class="cart-item">
                        <div class="row">
                            <div class="col-md-2">
                                <a href="{%  url 'core:product_detail' item.pid  %}">
                                    <img src="{{item.image}}" alt="Product Image" class="product-image">
                                </a>
                            </div>
                            <div class="col-md-6 product-details">
                                <a href="{%  url 'core:product_detail' item.pid  %}">
                                    <h4>{{item.title}}</h4>
                                </a>
                                <p>Product description lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
                                <div class="quantity-control">
                                    <button class="btn btn-sm btn-update"><i class="fas fa-sync-alt"></i></button>
                                    <input type="number" class="form-control quantity-input" value="{{item.qty}}">
                                    <button class="btn btn-sm btn-remove delete-item" data-item="{{product_id}}"><i class="fas fa-trash-alt" ></i></button>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <h4>{{item.price}}/Quantity</h4>
                            </div>
                        </div>
                    </div>
                    <!-- More cart items can be added dynamically here -->
                </div>
                {%  endfor  %}
                <div class="col-md-4">
                    <div class="cart-item total-section">
                        <h3>Total: <span class="total">{{cart_total_ammount}}</span></h3>
                        <button class="btn btn-checkout">Proceed to Checkout</button>
                    </div>
                </div>
            </div>
        </div>
        <script src="{% static 'assets/js/cart.js' %}"></script>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    </main>
    </body>

this hole code is not deleting products from cart page. Please help me out with this

Please help me out with this

running a service file befor bootstrap function in nestjs

I have create a microService for shearing Proto files (server). and i have module and service for calling this.

now in my (client), i want to call that microservice as soon as my application started. I already use onApplicationBootstrap() in my app.module file. but thats not work, because I use onModule init for my grpc client config in other modules. is there any way to run this, befor any other modules?