How can I access bucket elements from Google Cloud Storage using React/Vite?

I am trying to list all the items in my bucket using React with vite and I don’t understand why I am unable to do it. I am new to web-development in general, so a lot of the Docs tutorials are hard to follow. I am trying to access images from my GCS bucket and programatically list them in my react app.

I have used npm install @google-cloud/storage and I am trying to import it in my file like so: import { Storage } from "@google-cloud/storage";

however, I am getting an error:

TypeError: Cannot read properties of undefined (reading 'from')
    at node_modules/safe-buffer/index.js (index.js:12:12)
    at __require (chunk-5WRI5ZAA.js?v=bf5a1ca7:8:50)
    at node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js (ecdsa-sig-formatter.js:3:14)
    at __require (chunk-5WRI5ZAA.js?v=bf5a1ca7:8:50)
    at node_modules/google-auth-library/build/src/auth/oauth2client.js (oauth2client.js:20:21)
    at __require (chunk-5WRI5ZAA.js?v=bf5a1ca7:8:50)
    at node_modules/google-auth-library/build/src/auth/computeclient.js (computeclient.js:19:24)
    at __require (chunk-5WRI5ZAA.js?v=bf5a1ca7:8:50)
    at node_modules/google-auth-library/build/src/auth/googleauth.js (googleauth.js:24:25)
    at __require (chunk-5WRI5ZAA.js?v=bf5a1ca7:8:50)

I am very confused and have tried to use:
import * as Storage from '@google-cloud/storage' ,
import * as storage from '@google-cloud/storage'; const client = new storage.Storage(); , and

import * as storageModule from "@google-cloud/storage";
const { Storage } = storageModule;
const storage = new Storage();

but they give the same error which makes me think that I didn’t install GCS properly. I tried using npm install --save @google-cloud/storage as well but no change.

I also did npm install and re-run the application but nothing happened.

This is my simple code:

//getImages.js
import { Storage } from "@google-cloud/storage";

const bucketName = "my-bucket-name";
const storage = new Storage({
  keyFilename: "path/to/my/service-account.json",
});

export async function listFiles() {
  // Lists files in the bucket
  try {
    const [files] = await storage.bucket(bucketName).getFiles();

    console.log("Files:");
    files.forEach((file) => {
      console.log(file.name);
    });
  } catch (error) {
    console.error("Error listing files:", error);
  }
}

and this is my component:

import "./Gallery.css";
import { listFiles } from "../../utils/api/getImages";
import { useEffect, useState } from "react";

const Gallery = () => {
  const [images, setImages] = useState([]);

  useEffect(() => {
    async function fetchImages() {
      try {
        const urls = await listFiles();
        console.log(urls);
        setImages(urls);
      } catch (error) {
        console.error(error);
      }
    }

    fetchImages();
  }, []);

  console.log(images);
  return (
    <>
      <div>
        <h2>Gallery</h2>
        <div className="image-grid">
          {images.map((url, index) => (
            <img
              key={index}
              src={url}
              alt={`Image ${index}`}
              className="gallery-image"
            />
          ))}
        </div>
      </div>
    </>
  );
};

export default Gallery;

here are my package.json:

{
  "name": "website",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "@google-cloud/storage": "^7.12.0",
    "gsap": "^3.12.5",
    "react": "^18.3.1",
    "react-dom": "^18.3.1"
  },
  "devDependencies": {
    "@types/react": "^18.3.3",
    "@types/react-dom": "^18.3.0",
    "@vitejs/plugin-react": "^4.3.1",
    "eslint": "^8.57.0",
    "eslint-plugin-react": "^7.34.3",
    "eslint-plugin-react-hooks": "^4.6.2",
    "eslint-plugin-react-refresh": "^0.4.7",
    "react-router-dom": "^6.26.0",
    "vite": "^5.3.4"
  }
}

and package-lock.json:

{
  "name": "website",
  "version": "0.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "website",
      "version": "0.0.0",
      "dependencies": {
        "@google-cloud/storage": "^7.12.0",
        "gsap": "^3.12.5",
        "react": "^18.3.1",
        "react-dom": "^18.3.1"
      },
      "devDependencies": {
        "@types/react": "^18.3.3",
        "@types/react-dom": "^18.3.0",
        "@vitejs/plugin-react": "^4.3.1",
        "eslint": "^8.57.0",
        "eslint-plugin-react": "^7.34.3",
        "eslint-plugin-react-hooks": "^4.6.2",
        "eslint-plugin-react-refresh": "^0.4.7",
        "react-router-dom": "^6.26.0",
        "vite": "^5.3.4"
      }
    }, 
...

and vite.config.js if needed:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
})

Let me know if some of these are not needed (and why if possible) and I’ll delete to make the question better.

Any help and guidance would be appreciated, if I have understood something wrong, please explain why and how so that I can properly fix my code!

Thank you!

How do I fix my Javascript function? I’m having trouble defining and using this function

In this section of code, I’m trying to define ‘weaponselector’ as a certain value based on which button is clicked. this is a pretty basic question and I’m sure the result is just to change the function to a variable or something simple like that, but I’ve been stuck on it for a bit.

let wepo1=1;
let wepo2=2; 
let wepo3=3;
let wepo=0;


function weaponselector {
}



document.querySelector("button[name='shotgun/parent']").addEventListener("click",function() {
    weaponselector(wepo + wepo1);   
});

document.querySelector("button[name='pistol']").addEventListener("click",function() {
    weaponselector(wepo+wepo2);     
});

document.querySelector("button[name='rifle']").addEventListener("click",function() {
    weaponselector(wepo+wepo3); 

(The addition of some later code that references the ‘weaponselector’ function
there may be something wrong with this code too, and feel free to help me with that if you’d like too. I’m new to using JS so I’m having a lot of pretty explainable errors)


if (weaponselector=1){ 
    let weapon="shotgun" === {
        weapondamage:20
    };
}
if (weaponselector=2) {
    let weapon="pistol" === {
        weapondamage:5
    };
}

if (weaponselector=3) {
    let weapon="rifle" === {
        weapondamage:10 
    };
}

Asynchronous Fetch in Javascript

I need to make a call to a file named chiamata_preventivo.php, which takes about 10 minutes to respond. While this page is being processed, I would like to open a new tab to dashboard.php to allow the user to navigate while the request is being processed. The issue is that the call is blocking, and I’m unable to make it work with fetch() or an AJAX call.

Main file (this script is in the HTML head):

<script>
        document.addEventListener("DOMContentLoaded", async function() {
            try {
                const response = await fetch('chiamata_preventivo.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ datiJson: <?php echo $json; ?> })
                });
                const data = await response.json();
                console.log(data);

                // Open the dashboard in a new tab
                window.open("../../common_page/dashboard.php", "_blank");
            } catch (error) {
                alert('Error in request: ' + error);
            }
        });
    </script>

chiamata_preventivo.php

<?php
$_pageProfile = "*";
$nome_pagina = "chiamata_preventivo.php";

require_once $_SERVER['DOCUMENT_ROOT'] . '/common/database_connect.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/interfacce/bartolini/richiesta_bartolini.php';

header('Content-Type: application/json');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $input = file_get_contents('php://input');
    $dati = json_decode($input, true);
    $json = $dati["datiJson"];

    $response = dispatchRequestRCA(json_encode($json));
    echo json_encode($response);
    die();
}
?>

Any solutions?

How to Integrate a React Component from One React App into Another React App Using CDN

I’m trying to display a component from one React application within another React app using a CDN. Although the component works perfectly in its original application, I encountered an error related to the Use State hook when importing it via the CDN. This error is preventing the component from functioning correctly. How can I resolve this issue?

What I Tried and What I Expected:

I am rendering components from App 1 into App 2 by building App 1 and serving it through localhost on port 8000.

Desired Behavior:
The component should integrate seamlessly and function correctly within the host React app without any issues related to Use State.

Problem:
When importing the component via CDN, I encounter an error related to the use state, which does not occur when the component is used within its original application. How can I resolve this issue?

Screenshots and Configurations:

  1. App 1/Button.jsx App 1/Button.jsx
  2. App 2/index.html App 2/index.html
  3. App 2/App.js App 2/App.js
  4. App 1/Webpack.config.js App 1/Webpack.config.js

Error Faced:

Error Facing when rendering Error Facing when rendering

Can I use Adsense Ads in my website and Admob Ads in my google app (converted from same website) and coding what Ads to view?

I have an Adsense + Admob accounts, I created a website(Asp.net Framework 4.8, JavaScript on front-end), then I created a google app from my website (web-content), so the website and google app viewing the same contents.
So can I write a code to view the Adsense Ads when visitors open the website,
and view the Admob Ads when visitors open the google app? and is that legal ?
or just I must use one of the them ?

Please advice

Why Javascript’s WeakMap so weak? [closed]

In my experience with Lua, if I suspect that there is a memory leak with an object, I would place the object currently in use in a table and all newed objects in a WeakTable, using an ID as the index. During runtime, after performing garbage collection (gc), I can easily identify which objects have leaked by comparing these two tables. However, this approach is not feasible in JavaScript.

How to target from one parent’s child to another parent element?

Suppose I have four div classes as follow:

dFir
dSec
dSec
dThi

In this div, I have one li and have the following classes:

first
sec
sec
thi

I have to target from the first class to all dSec classes and change the background-color to #000.

The HTML I have written as follows”

<div class="dFir">
  <li class="first">fir</li>
</div>

<div class="dSec">
  <li class="sec">sec</li>
</div>

<div class="dSec">
  <li class="sec">thi</li>
</div>

<div class="dThi">
  <li class="thi">fou</li>
</div>

The css I have written as follows:

.first.active ~ .dSec{
   background-color: #000;
}

The js I have written as follow:

const free = document.querySelectorAll(".first");

    free.forEach(uff => {
        uff.addEventListener("click", () => {
            uff.classList.toggle("active");
        });
    });

I have to target from the first class to all dSec classes and change the background-color to #000.

How to Include Filename in Image Labels Using Lightbox2

I’m using Lightbox2 for displaying images in a gallery and would like to include the filename in the image label along with the image number and total count. By default, Lightbox2 allows customization of the label to show the image number and total using the albumLabel option in the format “Image %1 of %2”. I want to modify this to also show the filename of the image being viewed, e.g., “Image %1 of %2 – filename.jpg” just without the .jpg .

Here is the relevant part of my current Lightbox2 setup:

Lightbox.defaults = {
    albumLabel: 'Image %1 of %2',
    ...
};

Lightbox.prototype.imageCountLabel = function(currentImageNum, totalImages) {
    return this.options.albumLabel.replace(/%1/g, currentImageNum).replace(/%2/g, totalImages);
};

I’ve tried modifying the albumLabel to include a placeholder for the filename and adjusting the imageCountLabel method to replace it with the actual filename, but it’s not working as expected. Here’s what I’ve attempted:

Lightbox.defaults = {
    albumLabel: 'Image %1 of %2 - %3', // Added %3 for filename
    ...
};

Lightbox.prototype.imageCountLabel = function(currentImageNum, totalImages, filename) {
    return this.options.albumLabel
           .replace(/%1/g, currentImageNum)
           .replace(/%2/g, totalImages)
           .replace(/%3/g, filename);
};

Could anyone help me correct this setup or suggest a better way to include the filename in the image label?

Next.js : Performance Issues with Large Codebase Using App Router

I’m experiencing significant performance issues with my Next.js application. My project has grown substantially, and the build times and page loads have become noticeably slower. Here are the details of my setup:

Next.js Version: 15rc
Router: App Router
Codebase Size: Large with multiple complex pages and components

Problems:

Build Times: The build times have increased drastically as the codebase has grown.
Page Loads: Initial page loads are slow, and navigating between pages isn't as smooth as expected.

What I’ve Tried:

Code Splitting: I've implemented dynamic imports for some components, but the improvements are marginal.
Caching: Enabled server-side caching, but it hasn't significantly reduced the load times.
Analysis Tools: Used Webpack Bundle Analyzer to identify large bundles, but refactoring them hasn't helped much.
Optimization Tips: Followed various optimization tips from the Next.js documentation, but the performance gains are minimal.

Questions:

Are there specific configurations or best practices in Next.js 15rc that are particularly effective for large codebases?
How can I optimize the App Router for better performance in a large application?
Are there any known issues with Next.js 15rc that could be contributing to these performance problems?
Would upgrading to a stable release (if available) improve performance, or are there other recommended strategies?

Any advice or guidance on how to tackle these performance issues would be greatly appreciated!

Thank you!

DoesNotExist at /cart/cart_add/ product = Products.objects.get(id=product_id) product_id = None

My problem: DoesNotExist at /cart/cart_add/
When I try get product_id in request.POST
it`s value = None

Learn django but don`t now JS.
Perhaps:
Mistake in JS file
This code work with django4 (use django5)

jquery-ajax.js

$(document).ready(function () {
    var successMessage = $("#jq-notification");
    $(document).on("click", ".add-to-cart", function (e) {
        e.preventDefault();
        var goodsInCartCount = $("#goods-in-cart-count");
        var cartCount = parseInt(goodsInCartCount.text() || 0);
        var product_id = $(this).data("product-id");
        var add_to_cart_url = $(this).attr("href");
        $.ajax({
            type: "POST",
            url: add_to_cart_url,
            data: {
                product_id: product_id,
                csrfmiddlewaretoken: $("[name=csrfmiddlewaretoken]").val(),
            },
            success: function (data) {
                successMessage.html(data.message);
                successMessage.fadeIn(400);              
                setTimeout(function () {
                    successMessage.fadeOut(400);
                }, 7000);
                cartCount++;
                goodsInCartCount.text(cartCount);
                var cartItemsContainer = $("#cart-items-container");
                cartItemsContainer.html(data.cart_items_html);
            },
            error: function (data) {
                console.log("text");
            },
        });
    });

catalog.html

   
<a href="{% url "cart:cart_add" %}" class="btn add-to-cart" data-product-id="{{ product.id }}">  
{% csrf_token %}
<img class="mx-1" src="{% static "deps/icons/cart-plus.svg" %}" alt="Catalog Icon" width="32" height="32">

views.py

def cart_add(request): 
    
    product_id = request.POST.get("product_id") 
    product = Products.objects.get(id=product_id)
    user_cart = get_user_carts(request)
    cart_items_html = render_to_string(
        "carts/includes/included_cart.html", {'carts': user_cart}, request=request
    )    
    response_data =  {
        'masage': 'Тext', 
        'cart_items_html': cart_items_html, 
    }
    return JsonResponse(response_data) 

Traversal of Binary Tree in Order traversal and start “Reverse Order” if node has no children Javascript

Given a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to left, level by level). Once, node has not children go for parent where it has unvisited children.

     1 
   /   
  2     3
 /    /  
4   5 6    7

First traverse 1,2,4
Now 4 has no children
During back traverse in else part output 4, 2
then it should go to 2, 5

Now, 5 is end. Trace isVisited in parent nodes if any of the child is property isVisited as false.

5,2,1,3

Structure of tree with object array javascript

I was looking for this solution but reverse node traversal not working fine for me. Any suggestion welcome.

Sample data

[
    {
        "id": 15,
        "isVisited": true,
        "parentId": -1,
        "children": [
            {
                "id": 16,
                "isVisited": false,
                "parentId": 15,
                "children": [
                    {
                        "id": 14,
                        "isVisited": false,
                        "parentId": 16,
                        "children": [
                            {
                                "id": 12,
                                "isVisited": false,
                                "parentId": 14,
                                "children": [
                                    {
                                        "id": 13,
                                        "isVisited": false,
                                        "parentId": 12,
                                        "children": [
                                            {
                                                "id": 21,
                                                "isVisited": false,
                                                "parentId": 13
                                            },
                                            {
                                                "id": 20,
                                                "isVisited": false,
                                                "parentId": 13
                                            }
                                        ]
                                    }
                                ]
                            },
                            {
                                "id": 3,
                                "isVisited": false,
                                "parentId": 14,
                                "children": [
                                    {
                                        "id": 1,
                                        "isVisited": false,
                                        "parentId": 3,
                                        "children": [
                                            {
                                                "id": 18,
                                                "isVisited": false,
                                                "parentId": 1
                                            },
                                            {
                                                "id": 11,
                                                "isVisited": false,
                                                "parentId": 1
                                            }
                                        ]
                                    }
                                ]
                            },
                            {
                                "id": 2,
                                "isVisited": false,
                                "parentId": 14
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

Unable to scroll over a list of items in a container

I have a list of data which i am rendering in a panel, but for some reason i am unable to scroll over it with my mouse scroll wheel,panel has a scrollbar.

I am able to select the scrollbar and slide up and down with it.

.tree-container
{
    padding:10px;
    max-height: 150px;
    overflow-y: scroll;
}
<div class="tree-container">
  <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
</div>

In here I am rendering all the items once the data is fetched into a dive with tree-container class and each item in it have role-item class with text in it.

Views
RoleItem.js

    DE.Views.Roles = Common.UI.BaseView.extend(_.extend({
        el: '#left-panel-roles',

        template: _.template([
            '<div class="role-box layout-ct vbox">',
                '<div class="role-header">Roles',
                '<div class="role-btn-close"></div>',
                '</div>',
                '<div class="search-body">',
                    '<div class="search-container">',
                        '<input type="text" name="" spellcheck="false" class="form-control " placeholder="Search" data-hint="1" data-hint-direction="left" data-hint-offset="small">',
                    '</div>',
                    '<div class="options">',
                        '<label><input type="checkbox" class="chk-multi-select"><span>Multi Select</span></label>',
                        '<label><input type="checkbox" class="chk-unmapped"><span>Unmapped</span></label>',
                        '<label><input type="checkbox" class="chk-reorder"><span>Reorder</span></label>',
                    '</div>',
                '</div>',
                '<ul class="roles-list"></ul>',
            '</div>'
        ].join('')),

        renderTreeNode: function ($parent, nodes) {
            let me = this;
            nodes.forEach(node => {
                let $li = $('<li>')
                    .attr('data-id', node.id)
                    .addClass('role-item')
                    .append($('<span>').addClass('item-text').text(node.text));

                if (node.children && node.children.length > 0) {
                    $li.addClass('has-children');
                    let $childList = $('<ul>').addClass('child-list').hide();
                    me.renderTreeNode($childList, node.children);
                    $li.append($childList);
                }

                $li.attr('draggable', 'true');
                $parent.append($li);
            });
        },

    }, DE.Views.Roles || {}));

Controller
RoleItem.js

    DE.Controllers.Roles = Backbone.Controller.extend(_.extend({
        models: [],
        collections: ['Roles'],
        views: ['Roles'],

        onLaunch: function () {
            this.api = this.getApplication().getController('Viewport').getApi();
            this.panelRoles = this.createView('Roles');
            this.panelRoles.on('render:after', _.bind(this.onAfterRender, this));
            this._isDisabled = false;
            this.fetchRolesData();
        },

        fetchRolesData: function () {
            let me = this;
            this.api.fetchRolesTree(function (data) {
                me.fetchedRolesTree = data;
                me.renderTree();
            });
        },

        initTree: function () {
            this.$list = $('.roles-list', this.$el);
            this.$list.empty();
            this.$list.append('<div class="tree-container"></div>');
            this.$treeContainer = this.$list.find('.tree-container');
            this.showLoading();
        },

        renderTree: function () {
            if (!this.fetchedRolesTree) return;

            this.hideLoading();
            this.$treeContainer.empty();
            this.renderItems(this.fetchedRolesTree, this.$treeContainer);
            this.bindTreeEvents();
        },

        renderItems: function (items, $parent) {
            items.forEach(item => {
                let $item = $('<div class="role-item" data-id="' + item.id + '"></div>');
                $item.append('<span class="item-text">' + item.text + '</span>');
                if (item.children && item.children.length > 0) {
                    $item.addClass('has-children');
                    let $childContainer = $('<ul style="display:none;"></ul>');
                    this.renderItems(item.children, $childContainer);
                    $item.append($childContainer);
                }
                $parent.append($item);
            });
        },

        bindTreeEvents: function () {
            let me = this;
            this.$treeContainer.on('click', '.role-item > .item-text', function (e) {
                if (!$(e.target).hasClass('drag-handle') && !me.dragState.active) {
                    e.stopPropagation();
                    let $item = $(this).closest('.role-item');
                    $item.toggleClass('expanded');
                    $item.children('ul').slideToggle(200);
                    me.onSelectItem($item.data('id'), $(this).text());
                }
            });
        },

       //  other code
    }, DE.Controllers.Roles || {}));

Style for role items

.roles-list {
    list-style-type: none;
    padding-left: 0;
    height: calc(100% - 120px); /* Adjust based on your header and search heights */
    overflow-y: auto;
    position: relative;
    -ms-overflow-style: auto;
}


.roles-list ul {
    list-style-type: none;
    padding-left: 20px;
    padding-right: 20px;
}

.roles-list ul:first-child {
    padding-right: 15px;
}

.roles-list-container {
    padding: 10px;
}

/* Tree container */
.tree-container {
    padding: 10px;
    height: 100%;
    max-height: 500px;
    overflow-y: scroll;
    box-sizing: border-box;
}

I should be able to scroll with my mousewheel over the list of items in my panel.