Walk-through of modals re-rendering on every modal change

I have a series of modals that pop up and asks users questions for a car estimate site and every time a new modal is shown the whole component and child components re-render. this would be ok except on my problems modal submission the entire component re-renders and sets the current modal back to null. The goal is to have a ProblemSeverityModal show for every problem selected on the Problems modal. below is the component that re-renders every modal change, and here is the project in full on github

import React, { useState, useEffect } from 'react';
import EnterVin from './guide/EnterVIN';
import ConfirmCar from './guide/ConfirmCar';
import Problems from './guide/Problems';
import ProblemSeverityModal from './guide/ProblemSeverityModal';
import Quote from './guide/Quote';
import useVIN from '../utils/fetchVIN';
import useModalState from '../utils/useModalState';

const MemoizedConfirmCar = React.memo(ConfirmCar);
const MemoizedProblems = React.memo(Problems);
const MemoizedProblemSeverityModal = React.memo(ProblemSeverityModal);
const MemoizedQuote = React.memo(Quote);

const Guide = () => {
  const { currentModal, showModal, hideModal } = useModalState();
  const [vin, setVin] = useState('');
  const [selectedProblems, setSelectedProblems] = useState([]);
  const [currentProblemIndex, setCurrentProblemIndex] = useState(0);
  const [problemsWithSeverity, setProblemsWithSeverity] = useState([]);
  const { vinData, error } = useVIN(vin);

  const handleVinSubmit = (vin) => {
    setVin(vin);
    showModal('confirmCar');
  };

  const handleCarConfirm = () => {
    showModal('problems');
  };

  const handleProblemsSubmit = (problems) => {
    console.log('Problems submitted:', problems);
    setSelectedProblems(problems);
    setCurrentProblemIndex(0);
    setProblemsWithSeverity([]);
    showModal('problemSeverity');
  };

  const handleSeveritySubmit = (problemWithSeverity) => {
    setProblemsWithSeverity(prev => [...prev, problemWithSeverity]);
    
    if (currentProblemIndex < selectedProblems.length - 1) {
      setCurrentProblemIndex(prev => prev + 1);
    } else {
      showModal('quote');
    }
  };

  const handleQuote = () => {
    hideModal();
  };

  useEffect(() => {
    console.log('Modal set:', currentModal);
  }, [currentModal]);

  return (
    <>
      <EnterVin onSubmit={handleVinSubmit} />
      {vinData && (
        <>
          <MemoizedConfirmCar
            show={currentModal === 'confirmCar'}
            onHide={hideModal}
            onConfirm={handleCarConfirm}
            vinData={vinData}
          />
          <MemoizedProblems
            show={currentModal === 'problems'}
            onHide={hideModal}
            onSubmit={handleProblemsSubmit}
          />
          {selectedProblems.length > 0 && (
            <MemoizedProblemSeverityModal
              show={currentModal === 'problemSeverity'}
              onHide={hideModal}
              problems={[selectedProblems[currentProblemIndex]]}
              onSubmit={handleSeveritySubmit}
            />
          )}
          <MemoizedQuote
            show={currentModal === 'quote'}
            onHide={handleQuote}
            problems={problemsWithSeverity}
          />
        </>
      )}
      {error && <p>{error}</p>}
    </>
  );
};

export default Guide;

Best way to reduce requests using Zustand?

Im building an APP, basically a large scale CRUD, and want to make it the more scalable possible…

I was initially making a fetch every for every list in the app, when I thought about making global zustand states, and fetch all the data one time in the app.jsx, and instead of making fetch in every list, just use the state that is storing the list of objects I need.

Is this ok? Is there a better way to reduce Requests?

Just in case here is the global store I created.

import { create } from 'zustand'
import { getPatients } from '../hooks/patients/getPatients'
import { getServices } from '../hooks/services/getServices'
import { getProducts } from '../hooks/products/getProducts'
import { getRecords } from '../hooks/records/getRecords' // Assuming you have a getRecords function
import { getProductCategories } from 'src/hooks/products/categories/getProductCategories'
import { getProductProviders } from 'src/hooks/products/providers/getProductProviders'
import { getServiceCategories } from 'src/hooks/services/categories/getServiceCategories'
import { getServiceVariations } from 'src/hooks/services/variations/getServiceVariations'

export const useGlobalStore = create(set => ({
  patients: [],
  services: [],
  serviceCategories: [],
  serviceVariations: [],
  products: [],
  productCategories: [],
  productProviders: [],
  records: [],
  orders: [],
  isLoading: false,
  error: null,
  setRecords: records => set({ records }),
  
  setProducts: products => set({ products }),
  setPatients: patients => set({ patients }),
  setServices: services => set({ services }),
  setServiceVariations: serviceVariations => set({ serviceVariations }),
  setProductCategories: productCategories => set({ productCategories }),
  setProductProviders: productProviders => set({ productProviders }),
  setServiceCategories: serviceCategories => set({ serviceCategories }),
  fetchPatients: async () => {
    set({ isLoading: true, error: null })
    try {
      const patients = await getPatients()
      set({ patients })
    } catch (error) {
      set({ error: error.message })
    } finally {
      set({ isLoading: false })
    }
  },

  fetchServices: async () => {
    set({ isLoading: true, error: null })
    try {
      const services = await getServices()
      set({ services })
    } catch (error) {
      set({ error: error.message })
    } finally {
      set({ isLoading: false })
    }
  },

  fetchProducts: async () => {
    set({ isLoading: true, error: null })
    try {
      const products = await getProducts()
      set({ products })
    } catch (error) {
      set({ error: error.message })
    } finally {
      set({ isLoading: false })
    }
  },

  fetchRecords: async () => {
    set({ isLoading: true, error: null })
    try {
      const records = await getRecords()
      set({ records })
    } catch (error) {
      set({ error: error.message })
    } finally {
      set({ isLoading: false })
    }
  },
  fetchProdCategories: async () => {
    set({ isLoading: true, error: null })
    try {
      const productCategories = await getProductCategories()
      set({ productCategories })
    } catch (error) {
      set({ error: error.message })
    } finally {
      set({ isLoading: false })
    }
  },
  fetchProdProviders: async () => {
    set({ isLoading: true, error: null })
    try {
      const productProviders = await getProductProviders()
      set({ productProviders })
    } catch (error) {
      set({ error: error.message })
    } finally {
      set({ isLoading: false })
    }
  },
  fetchServCategories: async () => {
    set({ isLoading: true, error: null })
    try {
      const serviceCategories = await getServiceCategories()
      set({ serviceCategories })
    } catch (error) {
      set({ error: error.message })
    } finally {
      set({ isLoading: false })
    }
  },
  fetchServVariations: async () => {
    set({ isLoading: true, error: null })
    try {
      const serviceVariations = await getServiceVariations()
      set({ serviceVariations })
    } catch (error) {
      set({ error: error.message })
    } finally {
      set({ isLoading: false })
    }
  }
}))

Thanks in advance!

How to pass an object reference into a class that has access to the class methods in JS

Is it possible to “import” or “pass” a pre-defined object into a class that has access to methods on that class? Importantly, I need to ensure that I am only “passing” in a reference to the “massive_entity_obj” in the example and not re-creating/re-defining it.

class Distinct_Class {
   entities = null;

   constructor(massive_entity_obj) {
      this.entities = massive_entity_obj;
   }

   unique_func_1() {
      const some_value = "calcs based on unique data of Distinct_Class";
      return some_value;
   }
}

// defined in a separate module
massive_entity_obj = {
   property_1: {
      sub_property_a: "something",
      get sub_property_b() {
         // call a function in Distinct_Class in the context of Distinct_Class
         return this.unique_func_1(); // <-- this does not work
      },
   },
};

PHONE_REGISTRATION_ERROR / UNIMPLEMENTED error on a device using javascript

We are using TV devices which has Linux OS and javascript enabled it for UI. We are using google FCM to receive notifications. We are using a javascript library to get the fcm token by passing sender ID. It was all working fine. But from past few days we are getting PHONE_REGISTRATION_ERROR and UNIMPLEMENTED error / UNIMPLEMENTED error when we are trying to get the FCM token.

Below is the code snippet.


(async () => {                                                                                           
  try {                                                                                                                        
    const credentials = await register(senderID);
    const token = credentials.fcm.token;                                                                                                                                                               
    const persistentIds = [];
    await listen({ ...credentials, persistentIds }, onNotification);                                   
  } catch (e) {                                                                                                                                
    console.log("Error::" + e);                                                                                                                
  }                                                                                                                                            
})();

From past few days we are getting PHONE_REGISTRATION_ERROR and UNIMPLEMENTED error like below.

Register request has failed with Error=PHONE_REGISTRATION_ERROR
Retry... 1
Error::StatusCodeError: 501 - "{n  "error": {n    "code": 501,n    "message": "Operation is not implemented, or supported, or enabled.",n    "status": "UNIMPLEMENTED"n  }n}n"

Or some times UNIMPLEMENTED error alone and unable to get the token. I tried to restart the devices multiple times but no use.

I went through lot of questions online. All are showing issues with Android apps where the solution is like to clear cache, remove app and reinstall app. But I couldn’t find a solution for this javascript based program. Can someone please let me know if there is anyway to solve this issue.

Looking for a way to optimize my Javascript code

I am currently using a script that copies both the data and formatting of cells. While the code functions correctly, it is not performing efficiently. Even after incorporating a condition based on the last used row in Column C, the performance issues persist.

The process takes approximately 10 minutes to copy around 3,500 rows from five folders. Although I recognize my experience with this programming language is limited.

I would greatly appreciate any assistance from experts in identifying and resolving this issue.

Thank you.

function copyDataWithColorsToMasterSheet() {
  var folderIds = ['', '', '', '', ''];
  var masterSheetId = '';
  var masterSpreadsheet = SpreadsheetApp.openById(masterSheetId);
  var masterSheet = masterSpreadsheet.getActiveSheet();

  masterSheet.clear(); // Clear the master sheet to avoid duplicate data

  folderIds.forEach(function(folderId) {
    processFolder(folderId, masterSheet);
  });
}

function processFolder(folderId, masterSheet) {
  var folder = DriveApp.getFolderById(folderId);
  var files = folder.getFilesByType(MimeType.GOOGLE_SHEETS);

  var batchData = [];
  var batchBackgrounds = [];
  
  while (files.hasNext()) {
    var file = files.next();
    processSheet(file, batchData, batchBackgrounds);
  }

  if (batchData.length > 0) {
    var masterLastRow = masterSheet.getLastRow() + 1;
    var targetRange = masterSheet.getRange(masterLastRow, 1, batchData.length, batchData[0].length);
    targetRange.setValues(batchData);
    targetRange.setBackgrounds(batchBackgrounds);
  }

  var subfolders = folder.getFolders();
  while (subfolders.hasNext()) {
    var subfolder = subfolders.next();
    processFolder(subfolder.getId(), masterSheet);
  }
}

function processSheet(file, batchData, batchBackgrounds) {
  var spreadsheet = SpreadsheetApp.open(file);
  var sheet = spreadsheet.getSheets()[0];

  var lastUsedRowInColumnC = getLastUsedRowInColumnC(sheet);
  if (lastUsedRowInColumnC < 2) return;

  var lastColumn = sheet.getLastColumn();
  var dataRange = sheet.getRange(2, 1, lastUsedRowInColumnC - 1, lastColumn);
  
  var data = dataRange.getValues();
  var backgrounds = dataRange.getBackgrounds();
  
  // Append data and backgrounds to batch arrays
  batchData.push.apply(batchData, data);
  batchBackgrounds.push.apply(batchBackgrounds, backgrounds);
}

function getLastUsedRowInColumnC(sheet) {
  var columnC = sheet.getRange("C:C").getValues();
  for (var i = columnC.length - 1; i >= 0; i--) {
    if (columnC[i][0] !== "") {
      return i + 1; // Return the row number (1-based index)
    }
  }
  return 1; // Default to 1 if no data is found
}

i have two arrays. i would ilke to add an nested array from one to the other

array1 = [{"name": "jerry", "age": 22},{"name": "steve", "age": 44}]
array2 = [[30, 90], [50, 120]}

How can I loop through and for each of the array2 arrays add those to each item or array1 respectively?

the result am looking for is:

array3 = [{"name": "jerry", "age": 22, "mileage": [30, 90]},{"name": "steve", "age": 44, "mileage": [50, 120]}]

I have tried nested foreach‘s and it just pushes the first item from array2 into each object of array 1. I can’t for the life of me to get it to work. I have tried two for loops nested. same result as the foreach.

How do I remove the trailing space from elements that end with a newline?

I want to nest the text in certain HTML tags for clarity while editing, such that the opening tag, text, and closing tag each occupy their own line, like so:

<p>
  Lorem ipsum.
</p>

When this element is rendered, no space character is added to the front of the text; however, a space is added to the end of the text (as is visible when highlighted). I would like to remove this trailing space. Is there a simple, low-hack solution to get the browser to treat the ending newline like the starting newline instead of adding a space?

I imagine most people would just put up with this behavior or use a different formatting convention, but with how common it is to find trailing spaces on websites, I was curious if anyone had a solution.

ts-node isn’t working for a simple typescript application

I’m new to the NodeJS world.
I wanted to build an API with Express.js. I wrote my code with “Typescript” and now I want to run a super simple application

Node version: v22.3.0
npm version: 10.8.1

when I run

npx ts-node src/index.ts

I face this error.

TypeError: Unknown file extension ".ts" for <path-to-project>/src/index.ts
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:176:9)
    at defaultGetFormat (node:internal/modules/esm/get_format:219:36)
    at defaultLoad (node:internal/modules/esm/load:133:22)
    at async ModuleLoader.load (node:internal/modules/esm/loader:554:7)
    at async ModuleLoader.moduleProvider (node:internal/modules/esm/loader:435:45)
    at async ModuleJob._link (node:internal/modules/esm/module_job:106:19) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION

package.json

{
  "name": "api",
  "version": "1.0.0",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "devDependencies": {
    "@types/node": "^22.4.1",
    "ts-node": "^10.9.2",
    "typescript": "^5.5.4"
  },
  "dependencies": {
    "express": "^4.19.2"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "sourceMap": true,
    "outDir": "dist",
    "lib": ["esnext"],
    "esModuleInterop": true
  }
}

src/index.ts

import express from "express";

const app = express();

app.get("/", (req, res) => {
  res.status(200);
  res.json({
    message: "API",
  });
});

I’ve used tsx and it worked like a charm! I was wondering why ts-node sucks so bad?

How can I fix this userscript to work in a browser that has committed the inputs it uses to be its own shortcuts?

The idea of this userscript is that when browsing search results, you can hold different combinations of three keys to indicate whether that tag will be added to your search query with an AND, NOT or OR search operator.

The intended outcome is that holding Alt adds the next tag alongside with no symbol, Alt+Shift gives you the NOT operator and Alt+Shift+Control gives you the OR before the search is resubmitted.

var wrappers = document.querySelectorAll("td div.tags");
wrappers.forEach(function(div) {
    div.addEventListener('click', function(ev) {
        if (ev.altKey === true && ev.target.nodeName.toUpperCase() === "A") {
            ev.preventDefault();

            var anchor = ev.target,
                linkQuery = new URLSearchParams(anchor.search);
            var tag = linkQuery.get('taglist'),
                taglist;
            if (tag) {
                if (ev.shiftKey === true) tag = '-' + tag;
                else if (ev.ctrlKey === true) tag = '|' + tag;
                var pageQuery = new URLSearchParams(window.location.search);
                taglist = pageQuery.get('taglist').split(' ');
                if (taglist.indexOf(tag) === -1) taglist.push(tag);
                pageQuery.set('taglist', taglist.join(' '));

                window.location.search = pageQuery.toString();
            }
        }
    }, true);
});

I’d been using this made by a former colleague in Chrome on MacOS and I’d already had to make a gentle tweak for it to use sommand instead of shift as control+clicking brought up a context menu. The code itself works and has served me well.

I am now using Firefox and this problem has amplified. Control+click continutes to open a context menu. Shift+click opens the link in a new window without the effect of the script taking place, command+click does the same but opens a new tab in the background. Option still works as an equivalent for alt and I can successfully activate the first of the three combinations but this is where I got stuck.

Here is what I attempted between then and now.

  1. I tried to reconfigure Firefox but there seems to be no flexibility on any of the standard keyboard shortcuts.

The extent of my JavaScript is in my own userscripts pushing DOM elements around. I spent a few hours reading documentation and trying to fuse the example code into this script but I just couldn’t get anything going. I have very limited understanding of the syntax and find how things chain together and pass data between them unintuitive. But I unsuccessfully tried to apply my rudimentary programming ability in other languages to this situation using the documentation.

  1. I tried to replace the buttons being held down with other less contested buttons being held down but it seems like JS’s EventHandler sees those four as special. I tried to use ‘repeat’ but had no success, and tried to use other modifier style keys that were more easily recognised in an on/off state but they were either out of specification for Mac Firefox or I just couldn’t get any response from them. This seems like the most obvious and ideal solution.

  2. I tried to set variables with buttons and substitute the if (ev.shiftKey === true) bits with my own variables but I didn’t get anything to fire successfully.

  3. I swapped out ‘mouseover’ for ‘click’ as the event and it did work but this was not a practical solution and felt more like a sign to throw in the towel and ask for help.

Multer destination configuration not being applied

I’m trying to enable a profile pic feature in my web application. To do so, I’m using Express (4.19.2) for the server and Multer (1.4.5-lts.1) for multipart requests and file handling, however, Multer destination code seems to be ignored. I’ve followed some examples and landed the following Multer middleware code:

// Required modules
const fs = require('fs');
const path = require('path');
const multer = require('multer');

const validPictureExtensions = ['jpg', 'jpeg', 'png'];

// Profile picture configuration
const pictureStorage = multer.diskStorage({
    destination: (req, file, cb) => {
        // First check if resources directory exists
        if (!fs.existsSync(path.join(__dirname, '..', '..', 'resources'))) {
            console.info('Resources directory created.');
            fs.mkdirSync(path.join(__dirname, '..', '..', 'resources'));
        }
        
        // Then check if users directory exists
        if (!fs.existsSync(path.join(__dirname, '..', '..', 'resources', 'users'))) {
            console.info('Users directory created.');
            fs.mkdirSync(path.join(__dirname, '..', '..', 'resources', 'users'));
        }

        cb(null, 'users');
    },
    filename: (req, file, cb) => {
        const ext = file.originalname.split('.').pop();
        const name = `${req.user.id}.${ext}`;
        cb(null, name);
    }
});

const pictureFileFilter = (req, file, cb) => {
    const ext = file.originalname.split('.').pop();
    const isValid = validPictureExtensions.includes(ext);
    cb(null, isValid);
};

module.exports = {
    pictureMdw: multer({ pictureStorage, pictureFileFilter }),
}

Then, I’m using the previous middleware in a /users route, looking like this:

// Router
const router = require('express').Router();

// Middleware
const { pictureMdw } = require('./../middlewares/fileUpload');

// PUT
router.put('/:tagOrID/picture', pictureMdw.single('file'), userCont.updateUserPicture);

module.exports = router;

The relevant controller code after Multer middleware is executed is the following

await sharp(req.file.buffer)
                .resize({ width: 500, height: 500 })
                .jpeg()
                .toFile(path.join(__dirname, '..', '..', 'resources', 'users', `${tag}.jpeg`));

            res.sendStatus(200);

Everything works fine only if the necessary directories are previously created with something like mkdir -p resources/users, otherwise, I get an error. I’m yet to run a debugger but not even console.log('Here') gets printed when called inside the middleware configuration.
What could be happening here? Should I check for directory existence in the controller instead? Should I opt for a completely different approach instead?

Next.js Hydration Error is pointing out nesting error, however none is found?

I have been stuck on this problem for a couple hours now. I am creating a shopping cart implementation that will take the cart items (which are stored in localstorage) and display them. Here is a visual of what the cart looks like currently:
Picture of shopping cart

All of this is stored in a component called <OuterCart />. Each of the items is a rendering of the <CartItem /> component. Here is the code for both of them:

<OrderCart />

const OuterCart = ({cart, removeItem, changeQuantity}) => {
  return (
    <div className='px-3 text-gray-800'>
      <h1 className='my-10 text-2xl font-bold'>Shopping Cart</h1>
      <div className='grid grid-cols-10'>
        <div className='col-span-5 flex flex-col mb-5 border-b text-gray-800'>
          {cart.length === 0 ? <p>You have no items in your cart. <a href="/store" className='text-indigo-600'>Go shopping</a> to add some!</p> : ""}
          {cart.map((value, index, array) => {
            return(<CartItem key={index} value={value} removeItem={removeItem} changeQuantity={changeQuantity} />)
          })}
        </div>
        <div className='col-span-1'></div>
        <CartOrder cart={cart} />
      </div>
    </div>
  );
};

<CartItem />

const CartItem = ({value, removeItem, changeQuantity}) => {
  return (
    <div className='py-3 px-1 border-t flex grid grid-cols-3 gap-3'>
      <Image className='rounded-sm' src={img} alt='Product'></Image>

      <div className='ml-5 relative flex flex-col'>
        <span className='mb-1'>{value.name}</span>
        <span className='text-sm text-gray-500 mb-1'>{value.finish}, {value.size}</span>
        <span className='text-md'>${value.price.toFixed(2)}</span>
      </div>

      <div className='flex justify-between'>
        <div>
          <select className='outline-none border-2 border-gray-300 focus:border-indigo-700 px-3 pr-[2.5rem] py-1 rounded-md h-auto' onChange={(e) => changeQuantity(e, value.cartId)}>
            {[1,2,3,4,5].map(e => (
              <option
                key={e}
                selected={e === value.quantity}
              >
                {e}
              </option>
            ))}
          </select>
        </div>
        <div>
          <button className='text-gray-400 hover:text-red-600 hover:cursor-pointer transition outline-none'>
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4" onClick={() => {removeItem(value.cartId)}}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  )
};

Here’s the code for the page.js that puts these components together:

const Cart = () => {
  useEffect(() => {
    document.title = `Cart - Luca Cangelosi Photography`;
  });

  let items;
  try {
    items = JSON.parse(window.localStorage.getItem('cart')).items;
  } catch (e) {
    console.log(e);
    items = [];
  }

  const [cart, setCart] = useState(items);

  function changeQuantity(event, cartId) {
    let newCart = [...cart];
    for (let i=0; i<cart.length; i++) {
      if (cart[i].cartId === cartId) {
        newCart[i] = {
          ...newCart[i],
          quantity: parseInt(event.target.value),
        }
      }
    }
    setCart(newCart);
    window.localStorage.setItem('cart', "{"items":"+JSON.stringify(newCart)+"}");
  }

  function removeItem(cartId) {
    const newCart = cart.filter((item) => item.cartId !== cartId)
    setCart(newCart); 
    window.localStorage.setItem('cart', "{"items":"+JSON.stringify(newCart)+"}");
  }

  return (
    <div className='min-h-screen flex flex-col'>
      <Navbar />
      <div className="flex-1">
        <OuterCart cart={cart} removeItem={removeItem} changeQuantity={changeQuantity} />
      </div>
      <Footer />
    </div>
  );
};

export default Cart;

The shopping cart and all of the adjustments (adjusting quantity and removing items using the on-screen <select> and X button) work properly. However, I’m getting this React Hydration Error:
React Hydration Error

Does anyone know what this could mean? I’ve looked into the documentation and the issues that I could run into are accessing window.localstorage and having improper nesting of tags. I’ve looked and all my tags seem right (I could be wrong).

It’s also important to note that I’ll sometimes get an error in my VSCODE console that window is not defined, even if the cart (from window.localstorage) is properly accessed and retrieved.

What is the underlying error and how would I go about fixing it?

bxSlider undefined after adding via yarn to existing project

This is my first time working with yarn, so it could be a dumb/simple question. I’ve added jquery using yarn add jquery and I can see it in the modules folder, and also in the package.json and yarn.lock files. I added type="module" to the script tag and then added this to the top of my js file:

import jquery from 'jquery';
window.jQuery = jquery;
window.$ = jquery;

That got rid of jQuery not being defined. So now I’m trying to add bxSlider which was done successfully. Again, I see everything where it should be, but when I try to import it, I get this error: @parcel/core: Failed to resolve 'bxslider'.

What am I missing?

How to allow Cross-Origin using vite and express

I have two servers running on my computer. Server 1 uses Vite, and Server 2 uses Express. Server 1 is where I go on my browser, and Server 2 is for scripts I can’t run through Vite.

The home page (Server 1) has this script tag in it to call functions.

<script src="http://localhost:9050/Test" type="module"></script>

The problem is that I can’t access Server 2 due to CORS. I have looked this up for a while, and all I know is that I need to set a CORS header. How do I do this in Vite?


As soon as I posted this, I just realized that even if I did get a script from Server 2, Server 1 is still going to run the functions, so once I can get the script, I’m going to use an iframe or embed element so Server 2 runs the functions.

Why syft (sbom generator) can’t read package.json and package-lock.json? Am I doing something wrong?

At our company, we have been using syft + dependency-track for SCA (software composition analysis). Most of the time, this works fine but when we have to check for vulnerabilities on repositories that have a package.json or package-lock.json, syft is not able to identify any packages, even though they are declared in this file. It always returns 0 packages. We are using the following command for syft:

syft <repo-name.zip> -o cyclonedx-json=sbom.json

Any ideas what might be happening?

I tried running syft on some repos and I was expecting it to return the packages that were declared in the files package.json and package-lock.json

Change background color of P element on button click

I’m trying to write a segment that will change that background color of my

each time I click the button. So far, it only works after the first click and then I need to refresh, and then it works again but only once. I need it to work on repeated clicks.
My code so far:

document.getElementById("mybutton").addEventListener("click", function() {
    document.getElementById("p1").style.backgroundColor = randomColor;

});
function getRandomColor(){
    const letters = '0123456789ABCDEF';
    let color = '#';
    for(let i=0; i<6; i++) {
        color += letters[Math.floor(Math.random()*16)];
    }
    return color;
}
console.log(getRandomColor());
const randomColor = getRandomColor();