i have a 1700 image but it take 30 sec to render in react js [closed]

I’m working on a React project where I have around 1700 images (in .avif and .webp formats) stored in the src/assets/ folder. These images are used across multiple components — mostly displayed as carousels, product cards, and banners.

On local development, everything loads quickly and works perfectly.
However, after deploying to the production server, it takes up to 30 seconds or more to load all the images.

Environment:

  • Framework: React.js (Vite or Create React App)
  • Image formats: .avif, .webp
  • Image location: All images are inside src/assets/
  • Hosting: Deployed on a standard Node.js server (or static hosting like Vercel/Netlify — specify if applicable)

What I’ve Observed:

  • All images are imported via JavaScript (e.g., import carImage from ‘../assets/car1.avif’)
  • In DevTools (Network tab), images start loading from around 357ms and stretch up to 9 seconds or more
  • The bundle size is large, and all images seem to be bundled in JS during the build
  • When viewed locally, there’s no delay — images load instantly
  • I already use loading=”lazy” and image optimization formats like .avif/.webp

What I’ve Tried:

  • Checked and confirmed images are optimized (AVIF/WebP)
  • Added loading=”lazy” to all tags
  • Avoided large carousels preloading all images
  • No large JS logic or API delay — the issue is image loading specifically

My Goal:

  • I want to load images faster on the production site, ideally like they do in local.

How can I:

  • Prevent all 1700 images from loading at once?
  • Serve images more efficiently from the server?
  • Make use of caching or lazy-loading properly?

Possible Questions:

  • Should I move images from src/assets/ to public/ to serve them as static files?
  • Is bundling 1700 images in JavaScript a performance bottleneck?
  • Would it help to store images on a CDN or external static file host (like Cloudinary, AWS S3, etc.)?

How to validate autocomplete suggestion for API request

I am using Placekit for the forward geocoding and so far it works good, but I have an issue with the autocomplete. When I click on the suggestion from the autocomplete dropdown, it does not use this choice for the request. Instead it still makes a request for the input I typed in. How could I change this?
I created a stackblitz for this purpose. Public API inlcuded. Please use with caution.
https://stackblitz.com/edit/vitejs-vite-bovfbecx?file=src%2FApp.vue

JqueryUi datepicker Date Range modifications

I am using the basic Jqueryui datepicker, i need the date range with check in and check out but i need to add date + X days to the check out input.

How can i add X days to $.datepicker.parseDate( dateFormat, element.value

Here is the code

`

        $( function() {

        function getDate( element ) {
          var date;
          try {
            date = $.datepicker.parseDate( dateFormat, element.value  );
          } catch( error ) {
            date = null;
          }

          return date;
        }
          var dateFormat = 'dd MM yy',
            from = $( '#CheckIn' )
              .datepicker({
                minDate: 0,
                dateFormat: 'dd MM yy',
                defaultDate: '+1w',
                changeMonth: false,
                numberOfMonths: 1
              })
              .on( 'change', function() {
                to.datepicker( 'option', 'minDate', getDate( this ) );
              }),
            to = $( '#CheckOut' ).datepicker({
              dateFormat: 'dd MM yy',
              defaultDate: '+1w',
              changeMonth: true,
              numberOfMonths: 1
            })
            .on( 'change', function() {
              from.datepicker( 'option', 'maxDate', getDate( this ) );
            });
        } );`

When I select a date from Check In i want Check Out to only enable date + X days from the From selected day

Any help would be much appreciated

Thanks in advance

Problem with Promises and async/await in JavaScript [closed]

I’d like to consume data from a webservice and display it. The data has some dependencies on each other so that only one group of data can be displayed once all data of this group is read. All requests should start as fast as possible.

My code so far:

function asyncFetch(url = "", data = {}) {
  return fetch(url, {
      method: "POST",
      mode: "cors",
      cache: "no-cache",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    })
    .then(response => (response.json()))
    .catch(console.error);
}

const fetchOPDebitoren = () => {
  console.log(" fetch fetchOPDebitoren");

  return asyncFetch("http://server:3000/readOP", {
    token: "mytoken",
    options: {
      vpkt: "1000",
      bpkt: "6999"
    }
  });
};

const fetchOPKreditoren = () => {
  console.log("fetch fetchOPKreditoren");

  return asyncFetch("http://server:3000/readOP", {
    token: "mytoken",
    options: {
      vpkt: "7000",
      bpkt: "9999"
    }
  });
};

const fetchSalesData = () => {
  console.log(" fetch SalesData");

  return asyncFetch("http://server:3000/sales", {
    token: "mytoken",
    options: {
      von_pkt: "10000",
      bis_pkt: "99999"
    }
  });
};

const displayDueBarDashboard = () => {
  Promise.all([fetchOPDeb(), fetchOPKred()])
    .then(([op_data_deb, op_data_kred]) => {
      console.log(" fetch OPs completed");

      return new Promise((resolve) => {
        /* display the data */
        console.log("display op data");
      });
    })
    .catch((error) => console.error('Error display DueBarChart:', error))
};

const displaySalesChart = () => {
  Promise.all([fetchSalesData()])
    .then(([sales_data]) => {
      console.log("fetch SalesChart completed");

      return new Promise((resolve) => {
        /* display the data */
        console.log("display sales data");

      });
    })
    .catch((error) => console.error('Error display SalesChart:', error));
};


await Promise.all([
    displayDueBarDashboard(),
    displaySalesChart()
  ])
  .then(() => {
    console.log("All done, cleanup");
  });

As you can see, to display the DueBars the data of both fetchOP functions is needed.

With this code, the problem is now that the cleanup is called before all fetches are done and the display output is never shown.

fetch fetchOPDebitoren index.html:442:13
fetch fetchOPKreditoren index.html:465:13
fetch SalesData index.html:488:13
All done, cleanup index.html:563:13
fetch OPs completed index.html:539:14
fetch SalesChart completed

What am I doing wrong?

Also, in the fetch functions I must present a token. This token is requested with another call of asyncFetch which I have to wait for.

How can I implement that in the fetch functions without making them async?

Stop auto trigger buttons on an email during the forward action [closed]

We have a holiday booking system for employees and when somebody make a request, system generate an email to their manager. This email contains two buttons Approve and Reject so the manager can review and approve or reject it from the email rather than going to the system. This part is working as expected.

In some cases, managers forward the messages to holiday requester explaining the reason they cannot approve it (before rejecting the holiday request). When manager select forward message option, it seems the Approve button onclick event trigger automatically. not sure what is triggering this. Before they complete the forward message, they get a confirmation to say the holidays has been approved.

We tried this on number of computers with different AV software suspecting anti-virus tools responsible for this.

  1. What could be triggering this onclick event when forwarding the message?
  2. How to prevent it?

Any help would be appreciated

sample Php code for the message

        $headers = 'MIME-Version: 1.0' . "rn";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
        $headers .= 'From: Holiday System <[email protected]>' . "rn";

   $href_path = 'http:\\example.com\rauthpage.php'; 

        $style = '<head><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"><title>HUB</title></head>';

  $booking_ref = "8811624894907"; // example

            //$authkey = self::mdlProcessAuthenticateKey($booking_ref);
            $authkey = 123456789321654987; // example

            $subject = 'Mail Module Tester';
            $message = '<html lang="en">';
            $message .= $style;
            $message .= '<body>';
            $message .= 'Hi Manager,</br>';
            $message .= '<p>A holiday request has been made. please chose one of these</p>';
            $message .= '<h3>ACTIONS:</h3>';
            $message .= '<table>
                            <tr>
                                <td style="border-radius: 5px;" bgcolor="mediumseagreen">
                                <a href="' . $href_path . '?act=1&rauth=' . $authkey . '" target="_blank" style="padding: 8px 12px; border: 1px solid mediumseagreen;border-radius: 2px;font-family: Helvetica, Arial, sans-serif;font-size: 14px; color: #000000;text-decoration: none;font-weight:bold;display: inline-block;">Accept</a>
                                </td>
                                <td style="border-radius: 5px;" bgcolor="orangered">
                                <a href="' . $href_path . '?act=2&rauth=' . $authkey . '" target="_blank" style="padding: 8px 12px; border: 1px solid orangered;border-radius: 2px;font-family: Helvetica, Arial, sans-serif;font-size: 14px; color: #FFFFFF;text-decoration: none;font-weight:bold;display: inline-block;">Reject</a>
                                </td>
                            
                               
                            </tr>
                         </table>';
            $message .= '</body></html>';

            $to = '[email protected]';
            if (!is_null($to)) {
                mail($to, $subject, $message, $headers);
            }

Create a basic calculator in pure javascript [closed]

Can someone please tell me how to create basic calculator in pure javascript? with just an addition feature.

Function Calculator(){}
function Calculator() {
    var calculatorEl = document.getElementById('calculator');
    this.displayEl = calculatorEl.querySelector('#display');
    this.displayText = '';
    this.equation = [];

    // Bind event listener
    calculatorEl.addEventListener('click', this.handleButtonClick.bind(this));
  }

Basic Html:

<div id="calculator">
  <div id="display"></div>
  <div class="row">
    <button class="num-key">1</button>
    <button class="num-key">2</button>
    <button class="num-key">3</button>
  </div>
  <div class="row">
    <button class="num-key">4</button>
    <button class="num-key">5</button>
    <button class="num-key">6</button>
  </div>
  <div class="row">
    <button class="num-key">7</button>
    <button class="num-key">8</button>
    <button class="num-key">9</button>
  </div>
  <div class="row">
    <button class="num-key">0</button>
    <button class="op-key">+</button>
    <button id="solve-key">=</button>
  </div>
</div>

With the above basic html and function variable how can i create the basic calculator function?

Unable to update title

i install react-helmet-async here is my main.jsx file

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";
import HomeScreen from "./screens/HomeScreen.jsx";
import {
  RouterProvider,
  createBrowserRouter,
  createRoutesFromElements,
  Route,
} from "react-router-dom";
import ProductDetailsScreen from "./screens/ProductDetailsScreen.jsx";
import { Provider } from "react-redux";
import { store } from "./store.js";

import { HelmetProvider } from "react-helmet-async";

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route path="/" element={<App />}>     
      <Route path="/product/:id" element={<ProductDetailsScreen />} />
    </Route>
  )
);

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <HelmetProvider>
      <Provider store={store}>
        <RouterProvider router={router} />
      </Provider>
    </HelmetProvider>
  </StrictMode>
);

in my productDetailsscreen i am using this component Meta.jsx

import { Helmet } from "react-helmet-async";

const Meta = ({ title, description, keywords }) => {
  return (
    <Helmet>
      <title>{title}</title>
      <meta name="description" content={description} />
      <meta name="keywords" content={keywords} />
    </Helmet>
  );
};


export default Meta;

in my product details screen i am passing name description keywords but it doesn’t update my title etc

<Meta title="Title" description="description" keywords="keywords" />

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘message’)

I was following this guide https://youtu.be/hpgh2BTtac8?si=X6rZX3tMHl8yBgh4&t=52686 and on My orders page i have an error, orders dont loading. Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘message’). Im new at learning JavaScript and reduxjs and want ask for help. My code:

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { fetchUserOrders } from "../redux/slices/orderSlice";

  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { orders, loading, error } = useSelector((state) => state.orders);

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

  const handleRowClick = (orderId) => {
    navigate(`/order/${orderId}`);
  };

  if (loading) return <p>Loading ...</p>;
  if (error) return <p>Error: {error}</p>;

orderSlice

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

export const fetchUserOrders = createAsyncThunk(
  "orders/fetchUserOrders",
  async (_, { rejectWithValue }) => {
    try {
      const response = await axios.get(
        `${import.meta.env.VITE_BACKEND.URL}/api/orders/my-orders`,
        {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("userToken")}`,
          },
        }
      );
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

export const fetchOrderDetails = createAsyncThunk(
  "orders/fetchOrderDetails",
  async (fetchOrderDetails, { rejectWithValue }) => {
    try {
      const response = await axios.get(
        `${import.meta.env.VITE_BACKEND.URL}/api/orders/${orderId}`,
        {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("userToken")}`,
          },
        }
      );
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

const orderSlice = createSlice({
  name: "orders",
  initialState: {
    orders: [],
    totalOrders: 0,
    orderDetails: null,
    loading: false,
    error: null,
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchUserOrders.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchUserOrders.fulfilled, (state, action) => {
        state.loading = false;
        state.orders = action.payload;
      })
      .addCase(fetchUserOrders.rejected, (state, action) => {
        state.loading = false;
        console.log(action);
        state.error = action.payload.message;
      })
      .addCase(fetchOrderDetails.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchOrderDetails.fulfilled, (state, action) => {
        state.loading = false;
        state.orderDetails = action.payload;
      })
      .addCase(fetchOrderDetails.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload.message;
      });
  },
});

export default orderSlice.reducer;

Backend


const orderItemSchema = new mongoose.Schema(
  {
    productId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Product",
      required: true,
    },
    name: {
      type: String,
      required: true,
    },
    image: {
      type: String,
      required: true,
    },
    price: {
      type: Number,
      required: true,
    },
    size: String,
    color: String,
    quantity: {
      type: Number,
      required: true,
    },
  },
  { _id: false }
);

const orderSchema = new mongoose.Schema(
  {
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    orderItems: [orderItemSchema],
    shippingAddress: {
      address: { type: String, required: true },
      city: { type: String, required: true },
      postalCode: { type: String, required: true },
      country: { type: String, required: true },
    },
    paymentMethod: {
      type: String,
      required: true,
    },
    totalPrice: {
      type: Number,
      required: true,
    },
    isPaid: {
      type: Boolean,
      default: false,
    },
    paidAt: {
      type: Date,
    },
    isDelivered: {
      type: Boolean,
      default: false,
    },
    deliveredAt: {
      type: Date,
    },
    paymentStatus: {
      type: String,
      default: "pending",
    },
    status: {
      type: String,
      enum: ["Processing", "Shipped", "Delivered", "Cancelled"],
      default: "Processing",
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model("Order", orderSchema);

orderRoutes

const express = require("express");
const Order = require("../models/Order");
const { protect } = require("../middleware/authMiddleware");

const router = express.Router();

router.get("/my-orders", protect, async (req, res) => {
  try {
    const orders = await Order.find({ user: req.user._id }).sort({
      createdAt: -1,
    });
    res.json(orders);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "Server error" });
  }
});

router.get("/:id", protect, async (req, res) => {
  try {
    const order = await Order.findById(req.params.id).populate(
      "user",
      "name email"
    );
    if (!order) {
      return res.status(404).json({ message: "Order not found" });
    }
    res.json(order);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "Server error" });
  }
});

module.exports = router;

Backend works perfectly I checked through Postman.
I also debugged the action with console.log(action) and it gives this error
{type: ‘orders/fetchUserOrders/rejected’, payload: undefined, meta: {…}, error: {…}}

Looks like the problem is that payload is undefined, but i cant find an issue. Will be glad for any help

Electron JS Print Receipt with electron-pos-printer cuts page too soon and doesn’t print properly

I am building a POS system in Electron JS 35.0.1 and Angular 19. I have installed electron-pos-printer 1.3.6. The printer is triggered by a websocket notification from my backend. Currently the printer does not print the entire receipt. Rather it starts printing and then immediately stops with more than half the receipt stuck in the printer.
The printer is a standard thermal printer, POS80CUT model with USB interface.

Here is my print-receipt handler in my main.js

const { PosPrinter } = require("electron-pos-printer");

ipcMain.on("print-receipt", async (_, order) => {
  const options = {
    preview: false,
    margin: "0 0 0 0",
    copies: 1,
    printerName: printerName,
    timeOutPerLine: 400,
    pageSize: "80mm",
    silent: true,
  };

  const now = new Date().toLocaleString();
  const divider = "-".repeat(42);

  const items = order.items.map((item) => {
    const name = item.itemName.length > 25
      ? item.itemName.slice(0, 25) + "…"
      : item.itemName;
    const line = `${item.quantity.toString().padEnd(5)} ${name}`;
    return {
      type: "text",
      value: line,
      style: {
        fontSize: "12px",
        fontFamily: "monospace",
        lineSpace: "300px"
      },
    };
  });

  const data = [
    {
      type: "text",
      value: `ORDER ID: ${order.uuid}`,
      style: {
        fontSize: "20px",
        fontWeight: "bold",
        textAlign: "center",
      }
    },
    {
      type: "text",
      value: `Waiter: ${order.waiter.username}`,
      style: {
        fontSize: "12px",
        fontFamily: "monospace",
        fontWeight: "bold"
      },
    },
    {
      type: "text",
      value: `Date: ${now}`,
      style: {
        fontSize: "12px",
        fontFamily: "monospace",
        fontWeight: "bold"
      },
    },
    {
      type: "text",
      value: `Table: ${order.tableNumber}`,
      style: {
        fontSize: "12px",
        fontFamily: "monospace",
        fontWeight: "bold"
      },
    },
    {
      type: "text",
      value: divider,
      style: {
        fontSize: "12px",
        fontFamily: "monospace",
        textAlign: "left"
      },
    },
    {
      type: "text",
      value: "QTY                ITEM",
      style: {
        fontSize: "12px",
        fontFamily: "monospace",
        fontWeight: "bold",
        textAlign: "left"
      },
    },
    {
      type: "text",
      value: divider,
      style: {
        fontSize: "12px",
        fontFamily: "monospace",
        textAlign: "left"
      },
    },
    ...items
  ];

  try {
    await PosPrinter.print(data, options);
    console.log("✅ Receipt printed successfully");
  } catch (error) {
    console.error("❌ Print failed:", error);
  }
});

I have tried adding line spacing, line breaks, padding. They don’t work. And the printer doesn’t print for any other type other than text. So using table, html etc. is out of the question.

I have a long two-column HTML content structure and want to add “read more” buttons in between. How can I do it?

This is the format of the structure and each column has about 500 items.

<div class="row">
  <div class="col-md-6">
    <div><p>content</p></div>
    <div><p>content</p></div>
    ...
  </div>
  <div class="col-md-6">
    <div><p>content</p></div>
    <div><p>content</p></div>
    ...
  </div>
</div>

As it is quite long, I want to add 3-4 read more buttons at equal intervals to hide portion of the list and show it only when clicked. The “read more” button needs to be in the center for the entire row and not just each column.

I know how to build the functionality if it was a single column structure but in this case there are two columns and I am unsure of how to go around it.

Is it possible? How do I insert the “read more” button and where? How do implement the hide/show functionality?

Any pointers?

Received Node.js Error: node:internal/modules/cjs/loader:1228 throw err; Error: Cannot find module

after compiling my ts files when I ran my script.js file in the VS Code terminal, I received this error:

node:internal/modules/cjs/loader:1228
  throw err;
  ^

Error: Cannot find module '/Users/<username>/projects/course tree/course_tree/scripts/script.js'
    at Function._resolveFilename (node:internal/modules/cjs/loader:1225:15)
    at Function._load (node:internal/modules/cjs/loader:1055:27)
    at TracingChannel.traceSync (node:diagnostics_channel:322:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:220:24)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:170:5)
    at node:internal/main/run_main_module:36:49 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

Node.js v22.14.0

I honestly don’t know what is causing this error. I tried searching on Stack but I couldn’t find a solution to my problem.

I’m new to using TypeScript and I’m not too familiar with modules and modifying tsconfig.json.

My project folders is organized like this:

screenshot of project folders

My tsconfig.json is this:

{
  "compilerOptions": {
     "target": "es2016",
     "module": "Node16", 
     "moduleResolution": "nodenext",  
     "outDir": "./ts-out", 
     "esModuleInterop": true, 
     "forceConsistentCasingInFileNames": true,
     "strict": true, 
     "skipLibCheck": true  
  }, 
  "type": "module",
  "include": ["./ts-in"], 
  "exclude": [],
}

At the beginning I tried creating a d.ts file for each of my .ts files since I was receiving syntax errors in my import statements. Weirdly, the errors only went away when I replaced the relative path statements ../ts-out/<name-of-js-file>.js with ./<name-of-js-file>.js. However, I was able to compile the .ts files without any issues.

The error appears after I input node script.js. I’ve tried rm -rf node_modules npm install but it did not work. All modules are local and created by me so I’ve been using relative paths in all my import statements.

Theses errors didn’t occur at all when I initially placed all my .js and .ts files in a single folder with my tsconfig.json (My problems only started once I started to organize my files).

I’d be grateful if someone could point me in the right direction on how to fix this.

How i can show images in angular from my mysql db?

Im doing the frontend and backend of an it shop, to save the images of every product i have a blob column in the product table (dont know if its the best option but dont know another one better), the boss tell me to do an external app to add the an image to every product directly to the db.

private void addImage() {
    String selected = tableView.getSelectionModel().getSelectedItem().getDescripcion();
    System.out.println("Intentando añadir imagen al artículo: " + selected);
    if (selected == null) {
        showAlert("Error", "Seleccione un artículo primero para añadir una imagen.");
        return;
    }

    try {
        PreparedStatement pstmt = connection.prepareStatement("SELECT Imagen FROM articulos WHERE Descripción = ?");
        pstmt.setString(1, selected);
        ResultSet rs = pstmt.executeQuery();
        if (rs.next() && rs.getString("Imagen") != null) {
            showAlert("Error", "El artículo ya tiene una imagen. Use el botón 'Actualizar' para cambiarla.");
            return;
        }

        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().add(
            new FileChooser.ExtensionFilter("Images", "*.png", "*.jpg", "*.jpeg")
        );
        File file = fileChooser.showOpenDialog(null);

        if (file != null) {
            String base64Image = convertImageToBytes(file);
            if (base64Image != null) {
                pstmt = connection.prepareStatement("UPDATE articulos SET Imagen = ? WHERE Descripción = ?");
                pstmt.setString(1, base64Image);
                pstmt.setString(2, selected);
                pstmt.executeUpdate();
                System.out.println("Imagen añadida correctamente al artículo: " + selected);
                displayImage(selected);
            } else {
                showAlert("Error", "Error al convertir la imagen");
            }
        }
    } catch (SQLException e) {
        System.out.println("Error al añadir imagen: " + e.getMessage());
        showAlert("Error", "Error al añadir imagen: " + e.getMessage());
    }
}

private String convertImageToBytes(File imageFile){
    byte[] imageBytes = null;
    try(ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileInputStream fis = new FileInputStream(imageFile)) {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }
        imageBytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

In the app u just select a product from the db an select an img from your pc, here i dont have a problem the image saves succesfully and even shows itself if u click in the same product again, in the springboot controller i get the product with his image:

@GetMapping("/ofertas")
public ResponseEntity<List<ArticuloDTO>> getArticulosEnOferta() {
    List<Articulo> articulos = ArticuloService.obtenerArticulosEnOferta();

    List<ArticuloDTO> articulosDTO = articulos.stream().map(a -> new ArticuloDTO(
            a.getId_articulo(),
            a.getNombre(),
            a.getPrecio_medio(),
            a.isRebajado(),
            a.getPrecioRebajado(),
            a.getImagen() != null ? Base64.getEncoder().encodeToString(a.getImagen()) : null
    )).collect(Collectors.toList());

    return ResponseEntity.ok(articulosDTO);
}

but when i try to show that pic in angular i get an error, normally a loop where the page try to process the image all the time getting a lot of errors in the console log every second.i added some logs to see if i get the blob column from the db, and yes i get it so the problem should be when angular try to process the img.

cargarProductosEnOferta() {
    this.isLoading = true;
    this.error = null;

    this.productService.getProductosEnOferta().subscribe({
        next: (productos) => {
            console.log('Productos cargados:', productos.length);
            this.productosEnOferta = productos;

            productos.forEach((producto, index) => {
                console.log(`Producto ${index + 1}:`, {
                    id: producto.id_articulo,
                    nombre: producto.nombre,
                    descripcion: producto.descripcion,
                    precio_medio: producto.precio_medio,
                    rebajado: producto.rebajado,
                    precioRebajado: producto.precioRebajado,
                    imagen: producto.imagen ? {
                        tipo: typeof producto.imagen,
                        longitud: producto.imagen.length,
                        muestra: typeof producto.imagen === 'string' 
                            ? producto.imagen.substring(0, 50) + '...' 
                            : 'byte array'
                    } : 'sin imagen'
                });
            });

            if (productos.length > 0) {
                console.log('Estructura completa del primer producto:', JSON.stringify(productos[0], null, 2));
            }

            this.isLoading = false;
        },
        error: (error) => {
            console.error('Error loading products:', error);
            this.error = 'Error al cargar los productos';
            this.isLoading = false;
        }
    });
}

sanitizeBase64Image(imageData: string): SafeUrl {
    if (!imageData) {
        return this.sanitizer.bypassSecurityTrustUrl('assets/default-product.jpg');
    }

    try {
        return this.sanitizer.bypassSecurityTrustUrl(imageData);
    } catch (error) {
        console.error('Error processing image:', error);
        return this.sanitizer.bypassSecurityTrustUrl('assets/default-product.jpg');
    }
}

<div class="ofertas-gallery" *ngIf="!isLoading && !error" 
     [style.gridTemplateColumns]="'repeat(' + calcularColumnas(productosEnOferta.length) + ', 1fr)'">
    <div class="oferta-card" *ngFor="let producto of productosEnOferta">
        <div class="oferta-imagen">
            <img [src]="sanitizeBase64Image(producto.imagen)" 
                 [alt]="producto.nombre"
                 class="product-image">
            <div class="oferta-badge" *ngIf="producto.rebajado">
                -{{calcularPorcentajeDescuento(producto)}}%
            </div>
        </div>
        <div class="oferta-info">
            <h3>{{producto.nombre}}</h3>
            <div class="oferta-precios">
                <span class="precio-original">{{producto.precio_medio}}€</span>
                <span class="precio-oferta" *ngIf="producto.rebajado">
                    {{producto.precioRebajado}}€
                </span>
            </div>
            <button class="btn-agregar-carrito" (click)="agregarAlCarrito(producto)">
                <i class="fas fa-shopping-cart"></i>
                Añadir al carrito
            </button>
        </div>
    </div>
</div>

Probably im just blind and the error is obviously but i really dont see it xd.

Added some logs to see if i get correctly the img from the db this is an example of a product i get: Estructura completa del primer producto: {
“id_articulo”: 1, //id from the product
“nombre”: “ADAPTADOR USB WIFFI 1200 MBPS NAN0”, // name of the product
“precio_medio”: 12.86, //Price
“rebajado”: true, //In sale
“precioRebajado”: 10, //Sale price
“imagen”: “data:image/jpeg;base64,LzlqLzRBQVFTa1pKUmdBQkFRQUFBUUFCQUFELzJ3QkRBQU1DQWdJQ0FnTUNBZ0lEQXdNREJBWUVCQVFFQkFnR0JnVUdDUWdLQ2drSUNRa0tEQThNQ2dzT0N3a0pEUkVORGc4UUVCRVFDZ3dTRXhJUUV3OFFFQkQvMndCREFRTURBd1FEQkFnRUJBZ1FDd2tMRUJBUUVCQVFFQkFRRUJB……… //The img chain,and yes its longer than this if anyone ask it

Circle Not Following SVG Path Correctly

I generated the SVG using Illustrator and am trying to add animation using the gasp lib. I want to move the circle along the path, but it’s not aligning properly. I’m not sure where I’m going wrong.

gsap.to("#c1", {
  motionPath: "#path1",
  duration: 20,
  ease: "none",
  repeat: -1
});
<svg viewBox="0 0 820 400" style="background-color: black;">
  <path stroke="green" id="path1" class="st1"
d="M113.44,47.01c10.18,2.21,29.71,8.81,40.9,22.37,21.44,25.99,4.39,57.68,20,83.87,8.48,14.22,28.92,30.73,85,32.75" />
  <circle id="c1" r="2" cx="-5" cy="-5" fill="red" />
</svg>

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/MotionPathPlugin.min.js"></script>

Update notification from PHP script to JavaScript using EventSource [closed]

I’m trying a simple notification in PHP and JavaScript. The idea is when data the server is updated the client page is updated.

On the server I have the following test PHP script:

<?php
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');

    $data = rand(0, 1000);
    print $data;
    flush();

On the page I have the following JavaScript:

init();

function init() {
    var eventSource = new EventSource('includes/notify.php', {
        withCredentials: true,
    });
    eventSource.onopen = event => {
        console.log('eventSource open')
    }
    eventSource.onmessage = event => {
        console.log(`eventSource ${event.data}`);
    };
    eventSource.onerror = event => {
        console.log(event);
    }
}

I’m running it from a real server, so I shouldn’t have any issues there.

I’m getting repeated open and error messages, so something’s not working.

When I click on the URL which appears in the error object (https:// … /includes/notify.php) the PHP script works.

What is the missing step to get the notification working?

onSubmit event is not called after onClick

This is test code. When I click update button, it calls the updateItem function and then handleSubmit function, but when I click delete button, it calls only removeItem function. Both buttons are type="submit" button types.

import React, { useState } from "react";

function MyForm() {
  const [items, setItems] = useState([
    { id: 1, name: "item1" },
    { id: 2, name: "item2" },
    { id: 3, name: "item3" },
  ]);

  const removeItem = (id: number) => {
    setItems(items.filter((item) => item.id !== id));
  };

  const updateItem = (id: number) => {
    setItems(
      items.map((item) => {
        if (item.id === id) {
          return { ...item, name: "test" };
        } else {
          return item;
        }
      })
    );
  };

  const handleSubmit = (event: any) => {
    event.preventDefault();
    console.log("submit");
  };

  return (
    <form onSubmit={handleSubmit}>
      <ul>
        {items.map((item) => (
          <li key={item.id}>
            {item.name}
            <button type="submit" onClick={() => removeItem(item.id)}>
              Remove
            </button>
            <button type="submit" onClick={() => updateItem(item.id)}>
              Update
            </button>
          </li>
        ))}
      </ul>
    </form>
  );
}

export default MyForm;

I expect that delete button call onClick event and then submit event like update button.