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?

Undefined split in index.js and throw error in webpack bootstrap

Hi everyone i just enccounter a weird reactJS error while building my project alert error message prom after adding “child_process”: false into falback of webpack.config.js to fix the error child_process undefined:

enter image description here

and another error

enter image description here
locate in index.js in node_modules > nodemon > lib > utils > index.js
and in webpack folder

It seem to occur at line with the context of using split for undefined value i think

    var noop = function () { };
    var path = require('path');
    const semver = require('semver');
    var version = process.versions.node.split('.') || [null, null, null];

At first i try to debug by simply delete process.versions.node.split(‘.’)

result into change:

    var version = [null, null, null];
    var version = [0, 0, 0];

2 post having the similar error that i follow is
post 1

post 2

I try according to issue #120

    var version = process.version.node.split('.') || [null, null, null]; //post 1
    var current = process.versions && process.versions.node && process.versions.node.split('.') || 
    []; //post 2

i noticed that the browser (Chrome) still alert error in it system as

    var version = process.versions.node.split('.') || [null, null, null];

After that i ask copilot and GPT, they said that my application was being poorly configure lead to let my webpack.config.js modified my nodemone (i use CRA to create project) and should include

    externals: {
      nodemon: 'nodemon'
    },

in module.exports in webpack.config.js to tell webpack to not modify the nodemon but nothing change.

but again nothing much change. I didn’t try npm install resolve because i believe that my problem didn’t come from resolve because i did debug webpack breaking change error “Undefinded fs” by adding fallback fs: false but i will try if you guys think other wise

TailwindCSS DarkMode styles not applied to elements when toggling ‘dark’ class to HTML tree

I’m encountering an issue with implementing dark mode styles in my web application. I’ve followed the recommended approach of using Tailwind CSS’s built-in dark mode support by adding the ‘dark’ class to the HTML tree, but for some reason, the dark mode styles are not being applied.

Specifically, I’m trying to get ‘dark:bg-bgDark’ to be applied when darkMode is toggled. Currently, the background stays constant to bg-bgLight.

My tailwind.config.js:

/** @type {import('tailwindcss').Config} */
export default {
  content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
  theme: {
    darkMode: 'selector',
    extend: {
      boxShadow: {
        'custom': '0 2px 4px rgba(0, 0, 0, 0.1)'
      },
    },
    screens: {
      'sm': {'max': '550px'},
    },
    colors: {
      bgLight: 'hsl(0, 0%, 98%)',
      textColor: 'hsl(200, 15%, 8%)',
      bgDark: 'hsl(207, 26%, 17%)'
    },
    fontSize: {
      'sm': ['0.875rem', { lineHeight: '1.25rem' }], 
      'md': ['1.2rem', { lineHeight: '1.75rem' }],
      'big': '28px'
    },
  },
  plugins: [],
};

My HomePage.jsx:

import { Header, CountryCard } from "../components";
import { SearchBar, Filter } from '../utils'
import countries from "../assets/data.json";
import useTheme from '../hooks/useTheme'

const HomePage = () => {
  const [toggleTheme, theme] = useTheme()
  return (
    <div className="bg-bgLight dark:bg-bgDark">
      <Header theme={theme} toggleTheme={toggleTheme} />
      <div className="flex m-10 justify-between">
        <SearchBar />
        <Filter countries={countries} />
      </div>

      <div className="flex flex-wrap justify-center">
        {countries.map((country) => (
          <CountryCard key={country.alpha3Code} country={country} />
        ))}
      </div>
    </div>
  );
};

export default HomePage;

useTheme.jsx:

import { Header, CountryCard } from "../components";
import { SearchBar, Filter } from '../utils'
import countries from "../assets/data.json";
import useTheme from '../hooks/useTheme'

const HomePage = () => {
  const [toggleTheme, theme] = useTheme()
  return (
    <div className="bg-bgLight dark:bg-bgDark">
      <Header theme={theme} toggleTheme={toggleTheme} />
      <div className="flex m-10 justify-between">
        <SearchBar />
        <Filter countries={countries} />
      </div>

      <div className="flex flex-wrap justify-center">
        {countries.map((country) => (
          <CountryCard key={country.alpha3Code} country={country} />
        ))}
      </div>
    </div>
  );
};

export default HomePage;

I tried using ‘class’ instead of ‘selector’ in the config for darkMode.

I made sure the class ‘dark’ was being applied and removed accordingly to the HTML element on the DOM when toggling darkMode.

I made sure local storage and state was updating properly.

needing to sign in to use custom API in google cloud

Hi there I created a custom API in google cloud but when I try to access the API it only gives me the google thing for signing into google cloud console

script for access API:

const axios = require('axios');
const { google } = require('googleapis');

// Load the service account key file
const serviceAccountKey = require('./serviceAccountKey.json');

// Configure Axios to use Google authentication
const auth = new google.auth.GoogleAuth({
  credentials: serviceAccountKey,
  scopes: ['https://www.googleapis.com/auth/cloud-platform']
});
axios.defaults.headers.common['Authorization'] = `Bearer ${auth.getAccessToken().then(response => response.token)}`;

// Define the URL of your API endpoint
const apiUrl = 'https://3002-cs-105746203933-default.cs-us-east1-vpcf.cloudshell.dev/api/userids/Dan';

// Make a GET request to the API endpoint
axios.get(apiUrl)
  .then(response => {
    // Handle successful response
    console.log('Response:', response);
  })
  .catch(error => {
    // Handle error
    console.error('Error:', error.message);
  });

the actual api code:

const express = require("express");
const mongoose = require("mongoose");

const PORT = process.env.PORT || 3002;

// Connect to MongoDB database
mongoose.connect("mongodb+srv://<username>:<password>@cluster0.aviwp.mongodb.net/CarboCredit");
const db = mongoose.connection;
db.on("error", console.error.bind(console, "MongoDB connection error:"));
db.once("open", function () {
  console.log("Connected to MongoDB");
});

// Define a schema for the userids "table" (sub-collection)
const userIdsSchema = new mongoose.Schema({
  // Define the fields relevant to the userids "table"
  // For example:
  id: Number,
  // Other fields...
});

// Define a model based on the schema
const UserIds = mongoose.model("CarboCredit", userIdsSchema, "userids");


const app = express();

app.get("/api/userids/:userId", async (req, res) => {
  try {
    // Get the userId from request parameters
    const { userId } = req.params;

    // Find a document in UserIds sub-collection with the given userId
    const user = await UserIds.findOne({username: userId});

    // If no document found with the given userId
    if (!user) {
      return res.status(404).json({ error: "User not found" });
    }

    // Document found, return it as JSON response
    res.json(user);
  } catch (err) {
    console.error("Error fetching user:", err);
    res.status(500).json({ error: "Internal server error" });
  }
});

app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});

the code gives me the correct output when I access it inside google cloud vm but I want to access it in another google cloud VM it gives me a link to log into google cloud VM and when I tried to through post mate it was the same issue and I when I try to login it gives me a 400 error I was wondering if this could be bypassed or dissabled somehow

JS How to access current value from a created popup dropdown menu?

I’m trying to get the selected option (value) of the dropdown menu in a variable but I’m having trouble with getting it stored because I’m getting errors about it not existing. I understand that html can have order issues but because the popup’s html elements are all written in a JS file’s function I’m not sure how to circumvent that.

picture of popup

Essentially, I’m trying to use something like this at a specific point to save the selected option.

var chosenGender = document.getElementById("mySelect").value;

This gives me a TypeError: document.getElementById(...) is null which, I believe means that it can’t find my mySelect element which agrees with all the other tests I’ve run. This happens even when I check for an element I created and id’ed immediately before leading me to believe that there’s just something I’m missing here. How would I go about detecting completely new html elements that were inserted only with js?

Not able to see data i’ve passed through an array. No error when checked in console too,it shows an empty array in console. (Im not using API)

ProductDetails.jsx
ProductDetailList.jsx

I’m currently working on a React project where I’m rendering product and delivery details using components. I have two components: ProductDetailsList.jsx and ProductDetails.jsx.

ProductDetailsList.jsx contains an array of product details and an array of delivery details, which are passed as props to the ProductDetails component. In ProductDetails.jsx, I map through these arrays to render the details in separate sections.

However, I’m facing an issue with rendering these details properly. Despite passing the props correctly, the details don’t seem to render as expected. I’ve checked the console logs within ProductDetails.jsx and confirmed that the props are being received correctly.

I’m not sure where the issue lies – whether it’s with the way I’m passing the props or with how I’m rendering them in the ProductDetails component.

Datatable set multiple title on excel sheet after excel export button click

I am using Datatable and correctly fetching data as expected but in a situation where I want to export data on excel button I want some data in A1 and B1 cell then my regular table content should export. I tried customize option of datatable but it didn’t work like I needed.

Here is my code:-

$("#boms-table").DataTable({
    "responsive": true,
    "lengthChange": false,
    "autoWidth": true,
    "paging": false,
    "searching": true,
    "info": false,
    "buttons": [{
            extend: 'excel',
            exportOptions: {
                columns: ':visible:not(.exclude)'
            },
            title: "",
            customize: function(xlsx) {
                var sheet = xlsx.xl.worksheets['sheet1.xml'];
                $('row:first c', sheet).attr('s', '50');
                var a1 = $('row c[r^="A1"]', sheet);
                a1.html('<is><t>' + materialPartcode + '</t></is>');
                var b1 = $('row c[r^="B1"]', sheet);
                b1.html('<is><t>' + materialDesc + " - BOM" + '</t></is>');
                $('row').eq(1).addClass('ignore');
                $('row c', sheet).each(function() {
                    if ($(this).index() > 1) {
                        var selectedRow = $(this).parent();
                        var columnIndex = $(this).index();
                        selectedRow.find('c[r^="A"]').eq(columnIndex).addClass('ignore');
                        selectedRow.find('c[r^="B"]').eq(columnIndex).addClass('ignore');
                    }
                });
                $('.ignore', sheet).attr('s', '2');
            },
        },
        {
            extend: 'pdf',
            exportOptions: {
                columns: ':visible:not(.exclude)'
            },
            title: materialPartcode + " - " + materialDesc + " - BOM",
        },
        {
            extend: 'print',
            exportOptions: {
                columns: ':visible:not(.exclude)'
            },
            title: materialPartcode + " - " + materialDesc + " - BOM",
        },
        'colvis'
    ],
}).buttons().container().appendTo('#boms-table_wrapper .col-md-6:eq(0)'); 

All I want is “materialPartcode” in A1 cell then “materialDesc” in B1 cell then all the table contents. Kindly help!!!

Front-End To Back-End Connection

I have a front end webpage using html, css and js. I also have a back end using python code. The project is basically a URL Shortener Website. How can I connect the front-end with the back-end without a database and without using flask in python?

#my back-end code

import pyshorteners

import pyperclip

link=input(“Enter the link: “)

shortener=pyshorteners.Shortener()

x=shortener.tinyurl.short(link)

print(x)

pyperclip.copy(x)

#the input in the textbox on front-end should be transferred to the back-end and stored in the variable “link”. How can I achieve that? The shortened URL should also be sent back to the front end.

We tried using flask but since it was an absolutely new topic, we were unable to implement it. I couldn’t understand importing “templates” file in flask. Hence, the template of website was not loaded properly and the code showed error.

I dont know how to integrate Django or Nodejs. If the solution requires adding of these, then how can I install or import them?

Why is {object promise} popping up when a function returns a number? I need it to return data


I am not sure why “[object promise]” pops up in this case. I have tried to get help but can’t figure it out.

let inputFile = convertToFile() + ' <-- Data';

And then here is the function.

async function convertToFile() {
    const fileInput = document.getElementById('filedata');
    const file = fileInput.files[0];
    const reader = new FileReader();

    return new Promise((resolve, reject) => {
        reader.onload = function(event) {
            const buffer = event.target.result;
            const hexString = Array.from(new Uint8Array(buffer))
                .map(byte => byte.toString(16).padStart(2, '0'))
                .join('');
            resolve(hexString);
            console.log(hexString);
        };

        reader.onerror = function() {
            reject(new Error('Error reading file'));
        };

        if (file) {
            reader.readAsArrayBuffer(file);
        } else {
            reject(new Error('No file selected'));
        }
    });
}

I am not sure why this doesn’t work but it should return the text. Please help I am desperate.

I tried to replace it with another function and it worked fine. The problem is it returns “[object promise]”

Furthermore, I have also tried “await”

let inputFile = await convertToFile() + ' <-- Data';

Why my input is not reseting? {react-router-dom}

I’m currently working on getting my reset button to effectively reset the search functionality. While the button itself is working as intended, I’m encountering an issue where the text input field doesn’t reset along with it. Strangely, both “query,” “searchText,” and “inputValue” seem to retain their values, and I’m struggling to find a solution to reset them as well. Any assistance on resolving this would be greatly appreciated. Thanks!

//This is my reset function
const onResetSearch = () => {
    event.preventDefault();
   setBusco(false);
   setSearchParams({});
   console.log(query, searchText, inputValue);
   onResetForm();
   navigate("/search")}

const [searchParams, setSearchParams] = useSearchParams(); //esto se hace asi nomas
const query = useMemo(() => searchParams.get("q"), [searchParams.get("q")]); 
const heroes = useMemo(() => (query ? getHeroesByName(query) : []), [query]); 
const { searchText, onInputChange, onResetForm } = useForm({searchText: query || ""});

const inputValue = searchText.trim();
const onSearchSubmit = (event) => {
event.preventDefault();
if (inputValue.length < 1 || !inputValue) return;
setSearchParams({ q: inputValue });};

<button onClick={onResetSearch}}
className="btn btn-outline-danger mt-2">Reset</button>

When I search something (https://i.stack.imgur.com/JQCAr.png)
When I press the reset button (https://i.stack.imgur.com/uCxpt.jpg)
You can see that superman is still there in the input

horizontal slide button does not work with grid display

I’m working on a website, and want a horizontal carrousel function. I’m using the grid display, and after many tutorials I found a suitable way to implement this. For some reason this js does not work well with the grid display. I’m a novice and do not now much about java script.

As I mentioned, I played around with different ways to horizontal scroll. I realized that many of these implementations does not really work with grid, but I don’t want to rewrite my entire code for this.