SwiperJs not working properly when rendering it conditionally

In my angular application, I have 4 swiper slide, which i want to render conditionally. But its not working properly. I have added images as well at bottom.

Issue – On initial load all swiper are rendering properly with 4 slides per view. But suppose if select swiper_1 then its showing 1 slide per view but according to swiperParam it should show 4 slide per view.
If I select others like swiper_2, or swiper_3, then its showing 4 slides per view, and then if i select all then all swiper are showing 4 slide per view except the previous selected swiper “swiper_2 or swiper_3”.

I think the parameters are not getting applied properly.

Typescript ->

import { CommonModule } from '@angular/common';
import { ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA, ElementRef, NgZone, QueryList, Renderer2, ViewChild, ViewChildren, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-swiper-testing',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './swiper-testing.component.html',
  styleUrls: ['./swiper-testing.component.scss'],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  encapsulation: ViewEncapsulation.None,
})
export class SwiperTestingComponent {

  constructor(private el: ElementRef, private cdRef: ChangeDetectorRef, private ngZone: NgZone, private renderer: Renderer2) { }

  @ViewChild('swiper_1') swiper_1!: ElementRef;
  @ViewChild('swiper_2') swiper_2!: ElementRef;
  @ViewChild('swiper_3') swiper_3!: ElementRef;
  @ViewChild('swiper_4') swiper_4!: ElementRef;

  selectedCategories: string = 'all';

  swiperParams = {
    loop: false,
    slidesPerView: 1,
    spaceBetween: 24,
    breakpoints: {
      640: {
        slidesPerView: 2,
      },
      1024: {
        slidesPerView: 3,
      },
      1200: {
        slidesPerView: 4,
      },
      1500: {
        slidesPerView: 4.5,
      },
      1700: {
        slidesPerView: 5,
      },
      1900: {
        slidesPerView: 5.5,
      },
    },
    navigation: true,
  };
  
  
  ngAfterViewInit() {
    this.swiper_1Swiper();
    this.swiper_2Swiper();
    this.swiper_3Swiper();
    this.swiper_4Swiper();
  }

  categoriesSelect(value: string) {
    if (this.selectedCategories === value) return;
  
    this.selectedCategories = value;
    this.cdRef.detectChanges();
  
    // Let Angular fully update the view first
    this.ngZone.runOutsideAngular(() => {
      setTimeout(() => {
        this.ngZone.run(() => {
          if (value === 'all' || value === 'swiper_1') this.swiper_1Swiper();
          if (value === 'all' || value === 'swiper_2') this.swiper_2Swiper();
          if (value === 'all' || value === 'swiper_3') this.swiper_3Swiper();
          if (value === 'all' || value === 'swiper_4') this.swiper_4Swiper();
        });
      }, 0);
    });
  }
  
  swiper_1Swiper() {
    if (this.swiper_1?.nativeElement) {
      const swiperEl = this.swiper_1.nativeElement;
      Object.assign(swiperEl, this.swiperParams );
      swiperEl.initialize();
    }
  }
  
  
  swiper_2Swiper() {
    if (this.swiper_2?.nativeElement) {
      const swiperEl = this.swiper_2.nativeElement;
      Object.assign(swiperEl, this.swiperParams);
      swiperEl.initialize();
    }
  }
  swiper_3Swiper() {
    if (this.swiper_3?.nativeElement) {
      const swiperEl = this.swiper_3.nativeElement;
      Object.assign(swiperEl, this.swiperParams);
      swiperEl.initialize();
    }
  }
  swiper_4Swiper() {
    if (this.swiper_4?.nativeElement) {
      const swiperEl = this.swiper_4.nativeElement;
      Object.assign(swiperEl, this.swiperParams);
      swiperEl.initialize();
    }
  }
  

}

HTML ->

<div>
    <div class="main">
        <div class="filter-container d-flex justify-content-between align-items-start">
            <button type="button" class="btn btn-primary selected" (click)="categoriesSelect('all')">All
                swiper</button>
            <button type="button" class="btn btn-primary" (click)="categoriesSelect('swiper_1')">swiper 1</button>
            <button type="button" class="btn btn-primary" (click)="categoriesSelect('swiper_2')">swiper 2</button>
            <button type="button" class="btn btn-primary" (click)="categoriesSelect('swiper_3')">swiper 3</button>
            <button type="button" class="btn btn-primary" (click)="categoriesSelect('swiper_4')">swiper 4</button>
        </div>
        <div class="d-flex flex-column gap-4 mt-48">

            <div class="cards-swiper-container"
                *ngIf="selectedCategories === 'all' || selectedCategories === 'swiper_1'">
                <h4 class="mb-0">swiper_1 </h4>
                <div class="navigation-wrapper"></div>
                <swiper-container class="mySwiper" init="false" #swiper_1>
                    <swiper-slide *ngFor="let item of [1,2,3,4,5,6,7,8];">
                    </swiper-slide>
                </swiper-container>
            </div>
            <div class="cards-swiper-container" *ngIf="selectedCategories === 'all' || selectedCategories === 'swiper_2'">
                <h4 class="mb-0">swiper_2 </h4>
                <div class="navigation-wrapper"></div>
                <swiper-container class="mySwiper" init="false" #swiper_2>
                    <swiper-slide *ngFor="let item of [1,2,3,4,5,6,7,8];">
                    </swiper-slide>
                </swiper-container>
            </div>
            <div class="cards-swiper-container"
                *ngIf="selectedCategories === 'all' || selectedCategories === 'swiper_3'">
                <h4 class="mb-0">swiper_3 </h4>
                <div class="navigation-wrapper"></div>
                <swiper-container class="mySwiper" init="false" #swiper_3>
                    <swiper-slide *ngFor="let item of [1,2,3,4,5,6,7,8];">
                    </swiper-slide>
                </swiper-container>
            </div>
            <div class="cards-swiper-container" *ngIf="selectedCategories === 'all' || selectedCategories === 'swiper_4'">
                <h4 class="mb-0">swiper_4 </h4>
                <div class="navigation-wrapper"></div>
                <swiper-container class="mySwiper" init="false" #swiper_4>
                    <swiper-slide *ngFor="let item of [1,2,3,4,5,6,7,8];">
                    </swiper-slide>
                </swiper-container>
            </div>
        </div>
    </div>
</div>

All selected ->

enter image description here

Selected Swiper_1 ->

enter image description here

Selected Swiper_2 ->

enter image description here

Selected All again ->

enter image description here

Google Apps Script, getStartTime/getEndTime

Im currently working on a simple internal add-on for google calendar. When we click a event we will choose a option from a dropdown and click a button. When that happens, take the selected item with its corresponding attributes (working) and the events start and end- time. I cannot for the love of me get the time to work. What am I missing?

For now the logic is not there i just simply want to see the start and end times in the Log.

When this runs, and a item is selected, and we press the button we will in the log get the following:

  • Apr 23, 2025, 8:40:24 AM Info Selected customer ID: 1337
  • Apr 23, 2025, 8:40:24 AM Info Event start time: Invalid Date
  • Apr 23, 2025, 8:40:24 AM Info Event end time: Invalid Date

This is the script:

/**
 * Callback for opening a calendar event.
 * @param {Object} e The event object for the open callback.
 * @return {CardService.Card} The card to show to the user.
 */
function onCalendarEventOpen(e) {
  var cardBuilder = CardService.newCardBuilder();
  var customerData = getCustomersFromApi();

  var selectionInput = CardService.newSelectionInput()
      .setType(CardService.SelectionInputType.DROPDOWN)
      .setFieldName("dropdown_field")
      .setTitle("Select a customer");

  customerData.forEach(function(customer) {
    selectionInput.addItem(customer.name, customer.id, false);
  });

  var startTime = "";
  var endTime = "";

  // SAFELY extract start and end time strings from calendar event
  if (e && e.calendarEvent) {
    var event = e.calendarEvent;
    if (event.getStartTime && event.getEndTime) {
      startTime = event.getStartTime().toISOString();
      endTime = event.getEndTime().toISOString();
    }
  }

  var action = CardService.newAction()
    .setFunctionName("onTidsraporteraClick")
    .setParameters({
      startTime: startTime,
      endTime: endTime
    });

  var button = CardService.newTextButton()
      .setText("Tidsraportera")
      .setOnClickAction(action);

  var section = CardService.newCardSection()
      .addWidget(selectionInput)
      .addWidget(button);

  return cardBuilder.addSection(section).build();
}

/**
 * Callback for when the "Tidsraportera" button is clicked.
 * Logs the selected customer and the calendar event start/end times.
 * @param {Object} e The event object containing form inputs and parameters.
 * @return {CardService.ActionResponse}
 */
function onTidsraporteraClick(e) {
  try {
    var selectedCustomerId = e.commonEventObject.formInputs["dropdown_field"].stringInputs.value[0];
    Logger.log("Selected customer ID: " + selectedCustomerId);

    var startTime = new Date(e.parameters.startTime);
    var endTime = new Date(e.parameters.endTime);

    Logger.log("Event start time: " + startTime);
    Logger.log("Event end time: " + endTime);
  } catch (error) {
    Logger.log("Error in onTidsraporteraClick: " + error);
  }

  return CardService.newActionResponseBuilder()
    .setNotification(CardService.newNotification()
      .setText("Customer: " + selectedCustomerId + "nStart: " + startTime + "nEnd: " + endTime))
    .build();
}

This is a part of the appscript.json:

{
  "timeZone": "Europe/Berlin",
  "runtimeVersion": "V8",
  "oauthScopes": [
    "https://www.googleapis.com/auth/calendar.addons.execute",
    "https://www.googleapis.com/auth/script.locale",
    "https://www.googleapis.com/auth/calendar.readonly",
    "https://www.googleapis.com/auth/calendar",
    "https://www.google.com/calendar/feeds",
    "https://www.googleapis.com/auth/script.external_request"
  ],

Ive experimented with grabing it as a date, a string and then passing it to the onClick to then convert it back to Date. For this version we are getting Invalid date, but before that mostly I was getting Undefined so there is something wrong when i try to grab the events time.

How to populate a field in array?

How can I populate the Amount $ (Tax Included) field based on input from the respective Quantity field? E.g. When user enter a quality of 5 in the Flower row (Row #2), 5 is supposed to be populated in the respective Amount $ (Tax Included) row (Row #2).

Both the Quantity & Amount $ (Tax Included) fields are arrays.

<td align="right"><input class="amt" id="amt" name="amt[]" step="0.01" type="number" required /></td>
<td align="right" height="32" class="label"><span id="sum" name="sum[]">0.00&nbsp;</span></td>

I’m able to get the quantity value entered in the respective rows but I’m not sure how to populate the value into the respective Amount $ (Tax Included) row.

$(document).ready(function() {
var cnt = 0;


$('[name="amt[]"]').change(function() {         
    var amt_list = $("input[name^='amt']").map(function (idx, ele) {
        return $(ele).val();    
    }).get();

    cnt = amt_list.length;

    for (i = 0; i < cnt; i++) {
        if (!isEmpty(amt_list[i])) {
            alert(i);
            $("input[name='sum[i]']").html(amt_list[i]); // Stuck here
        }
    }
});     

});

enter image description here

Thanks in advance for any suggestions.

How to properly handle CSS animations in sync with JavaScript events?

I’m working on a project where I need to trigger a CSS animation in response to a JavaScript event, but I’m running into issues where the animation either doesn’t trigger correctly and plays multiple times when it should only happen once.

Specifically, I’m using a JavaScript click event to trigger a CSS animation on an element. The problem is that the animation continues to play even after the event is triggered once, and I need it to run only once per click.

I added an event listener for the click event, so when I click the cat, it adds the animate class to trigger the scaling animation. I expected the cat to scale up just once on the first click and not repeat, but instead, the animation keeps playing every time I click, and it doesn’t reset, causing it to repeat even after one click.

save and credit system management

web based in php and js

SET SQL_MODE = “NO_AUTO_VALUE_ON_ZERO”;
SET time_zone = “+00:00”;

— Customers Table
CREATE TABLE IF NOT EXISTS customers (
acc_number INT AUTO_INCREMENT PRIMARY KEY,
fname VARCHAR(255) NOT NULL,
lname VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
sex VARCHAR(10) NOT NULL,
age INT NOT NULL,
phone VARCHAR(20) NOT NULL,
image_path VARCHAR(2000) NOT NULL,
branch_name VARCHAR(33) NOT NULL,
pass VARCHAR(255) NOT NULL,
balance DECIMAL(10, 2) DEFAULT 0.00,
strt_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Employee Table
CREATE TABLE IF NOT EXISTS employee (
emp_id INT AUTO_INCREMENT PRIMARY KEY,
fname VARCHAR(255) NOT NULL,
lname VARCHAR(255) NOT NULL,
emp_username VARCHAR(255) UNIQUE NOT NULL,
email VARCHAR(255) NOT NULL,
pass VARCHAR(255) NOT NULL,
sex VARCHAR(10) NOT NULL,
age INT NOT NULL,
salary DECIMAL(10, 2) NOT NULL,
phone VARCHAR(20) NOT NULL,
files VARCHAR(2000) NOT NULL,
hire_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Admin Table
CREATE TABLE IF NOT EXISTS e_admins (
admin_id INT AUTO_INCREMENT PRIMARY KEY,
fname VARCHAR(255) NOT NULL,
lname VARCHAR(255) NOT NULL,
admin_username VARCHAR(255) UNIQUE NOT NULL,
email VARCHAR(255) NOT NULL,
pass VARCHAR(255) NOT NULL,
sex VARCHAR(10) NOT NULL,
age INT NOT NULL,
phone VARCHAR(20) NOT NULL,
files VARCHAR(2000) NOT NULL,
hire_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Branch Admin Table
CREATE TABLE IF NOT EXISTS branchs_admins (
branch_id INT AUTO_INCREMENT PRIMARY KEY,
fname VARCHAR(255) NOT NULL,
lname VARCHAR(255) NOT NULL,
b_username VARCHAR(255) UNIQUE NOT NULL,
sex VARCHAR(10) NOT NULL,
age INT NOT NULL,
b_email VARCHAR(255) UNIQUE NOT NULL,
pass VARCHAR(255) NOT NULL,
phone VARCHAR(255) NOT NULL,
files VARCHAR(255) NOT NULL,
hire_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Super Admin Table
CREATE TABLE IF NOT EXISTS super_admin (
sup_id INT AUTO_INCREMENT PRIMARY KEY,
fname VARCHAR(255) NOT NULL,
lname VARCHAR(255) NOT NULL,
sup_username VARCHAR(255) UNIQUE NOT NULL,
sex VARCHAR(10) NOT NULL,
age INT NOT NULL,
sup_email VARCHAR(255) UNIQUE NOT NULL,
pass VARCHAR(255) NOT NULL,
phone VARCHAR(255) NOT NULL,
files VARCHAR(255) NOT NULL,
hire_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Saving Table
CREATE TABLE IF NOT EXISTS saving (
save_id INT AUTO_INCREMENT PRIMARY KEY,
customer_acc INT NOT NULL,
save_amount DECIMAL(10,2) NOT NULL,
save_interest DECIMAL(5,2) NOT NULL,
interest_year VARCHAR(100) NOT NULL,
strt_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (customer_acc) REFERENCES customers(acc_number)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE customers
MODIFY acc_number INT NOT NULL;
ALTER TABLE saving
MODIFY customer_acc VARCHAR(20) NOT NULL,
DROP FOREIGN KEY saving_ibfk_1,
ADD FOREIGN KEY (customer_acc)
REFERENCES customers(acc_number);

— Loan Table
CREATE TABLE IF NOT EXISTS loan (
l_id INT AUTO_INCREMENT PRIMARY KEY,
customer_acc INT NOT NULL,
loan_status ENUM(‘pending’, ‘accepted’, ‘completed’, ‘canceled’) DEFAULT ‘pending’,
loan_amount DECIMAL(10,2) NOT NULL,
loan_interest DECIMAL(5,2) NOT NULL,
files VARCHAR(3000) NOT NULL,
strt_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (customer_acc) REFERENCES customers(acc_number)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Loan Payment Table
CREATE TABLE IF NOT EXISTS loan_pay (
p_id INT AUTO_INCREMENT PRIMARY KEY,
loan_id INT NOT NULL,
customer_acc INT NOT NULL,
loan_status ENUM(‘pending’, ‘accepted’, ‘completed’, ‘canceled’) DEFAULT ‘pending’,
loan_amount DECIMAL(10,2) NOT NULL,
loan_interest DECIMAL(5,2) NOT NULL,
strt_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (loan_id) REFERENCES loan(l_id),
FOREIGN KEY (customer_acc) REFERENCES customers(acc_number)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Transactions Table
CREATE TABLE IF NOT EXISTS transactions (
t_id INT AUTO_INCREMENT PRIMARY KEY,
customer_acc INT NOT NULL,
t_type ENUM(‘deposit’, ‘withdraw’) NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
t_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (customer_acc) REFERENCES customers(acc_number)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Other Bank Transactions Table
CREATE TABLE IF NOT EXISTS transaction_otherbanks (
t_id INT AUTO_INCREMENT PRIMARY KEY,
customer_acc INT NOT NULL,
from_bank ENUM(‘CBE’,’BOA’,’Zemen’,’otherbanks’) NOT NULL,
t_type ENUM(‘receive’, ‘send’) NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
t_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (customer_acc) REFERENCES customers(acc_number)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Feedback Table
CREATE TABLE IF NOT EXISTS feedback (
fe_id INT AUTO_INCREMENT PRIMARY KEY,
for_role ENUM(‘customers’, ’employee’, ‘e_admins’, ‘branchs_admins’, ‘super_admin’) NOT NULL,
txts VARCHAR(2000) NOT NULL,
feedback ENUM(‘suggestion’, ‘complaint’) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Contact Table
CREATE TABLE IF NOT EXISTS contact (
ct_id INT AUTO_INCREMENT PRIMARY KEY,
customer_acc INT NOT NULL,
contact_type ENUM(’email’, ‘call’) NOT NULL,
FOREIGN KEY (customer_acc) REFERENCES customers(acc_number)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Why is my user being logged out from my React Native app, using firebase/auth

I have a react native app where I use firebase/auth.

This is what I have in my package.json file:

"dependencies": {
    ....
    "@react-native-firebase/analytics": "^21.7.1",
    "@react-native-firebase/app": "^21.7.1",
    "firebase": "10.13",
    ....
}

Please let me know if I need to have something else in my dependencies.

This is my App.js file:

import { getAuth, signInWithEmailAndPassword, onAuthStateChanged } from "firebase/auth";

const App = () => {

  const [verified, setVerified] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  ...
  ...
  ...
  useEffect(() => {
      const auth = getAuth();
      const unsubscribe = onAuthStateChanged(auth, (user) => {
        if(user){
          setCurrentUser(user);
          setVerified(user.emailVerified);
        }else{
          setCurrentUser(null);
        }
      });
      return () => unsubscribe();
    }, []);
    ...
    ...
    ...
    if(!currentUser){
      return (
        <NavigationContainer>
          <AuthNavigator />
        </NavigationContainer>
      );
  }
  else if (currentUser && !verified){
    return (
      <NavigationContainer>
        <VerifyEmail setVerified={setVerified}/>
      </NavigationContainer>
    );
  }
  else{
    return (
      <Provider store={store}>
        <NavigationContainer>
          <MainNavigator />
        </NavigationContainer>
      </Provider>
    );
  }
};
  export default App;

Users can log in, they can log out, and for some STRANGE reason, which I can not figure out, after I leave my phone untouched for 20 minutes, they are once again logged out, without even touching the app.

What am I doing wrong?

navigator.mediaDevices.getDisplayMedia doesn’t show current tab as an option

Looked at similar answers and followed the guidelines there,but I can’t get the current tab to show up as an option in any browser that I’ve tried (Chrome, Edge, Opera). The rest of my code requires CropTarget, which is why I didn’t try FireFox, as it’s not supported.

Code that asks for permissions:

const stream = await navigator.mediaDevices.getDisplayMedia({
  video: { displaySurface: "browser", selfBrowserSurface: "include", preferCurrentTab: true }
});

And the user action that makes the function call:

<div class="row">
    <button onclick="captureElement('myId')">Capture</button>
</div>

I’ve also enabled Experimental Web Flag features in flags, but that has also not helped.

Is it possible to target the caller tab when using getDisplayMedia?

Trying to set a max-width to a column of text in a table the scrolls horizontally?

Is it possible to set a max-width to the third <col> such that the first table will wrap at that max-width, and the second table will not even reach that width but just fit the content?

Using min-width works for the first table but leaves the column too wide in the second table.

If no width styles are used, (since the table is wider than its parent element and all other columns are set to not wrap), the 3rd column wraps on just about each word. That’s why tried a minimum width.

The max-content style will not permit wrapping.

I don’t want to use a fixed width table otherwise.

There is only one table but the text content varies with each load of the tbody content; thus, one set of styles must work for both.

Thank you.

div {
  width:500px;
  overflow-x:auto;
  overflow-y:auto;
  border: 1px solid blue;
}

table {
  border-collapse: collapse;
  margin-bottom: 20px;
}
thead {
  background-color: rgb(200,200,200);
}

th,td {
  border: 1px solid gray;
  padding: 10px 20px;
}

td:not(:nth-child(3)) {
  white-space: nowrap;
}

table col:nth-child(3) {
  min-width:300px;
}

/*
table.cat_1 {
  width: max-content;
}

table.cat_1 col:nth-child(3) {
  max-width: 200px;
}
*/
<div class="prnt">
  <table class="cat_1">
    <colgroup>
      <col><col><col><col><col><col><col>
    </colgroup>
    <thead>
      <tr>
         <th>Id</th>
         <th>Size</th>
         <th>Text</th>
         <th>Col 4</th>
         <th>Col 5</th>
         <th>Col 6</th>
         <th>Col 7</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1001</td>
        <td>2028</td>
        <td>A line of text that exceeds the desired maximum width of third column.</td>
        <td>td 4 data</td>
        <td>td 5 data</td>
        <td>td 6 data</td>
        <td>td 7 data</td>
      </tr>
    </tbody>
  </table>
  <table class="cat_2">
    <colgroup>
      <col><col><col>
    </colgroup>
    <thead>
      <tr>
         <th>Id</th>
         <th>Size</th>
         <th>Text</th>
         <th>Col 4</th>
         <th>Col 5</th>
         <th>Col 6</th>
         <th>Col 7</th>         
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1001</td>
        <td>2028</td>
        <td>A short line.</td>
        <td>td 4 data</td>
        <td>td 5 data</td>
        <td>td 6 data</td>
        <td>td 7 data</td>        
      </tr>
    </tbody>
  </table>
</div>

   

How can I memoize a JS Object on a per item basis?

I am positive that this is a very easy question to solve, however my attempts have yielded no results and no LLM is giving me an answer that works. I have the below memoizedList which works fine. The problem is it has 50 items in it, and every time one item changes, every single list item gets rerendered which is causing lag.

const [selectorInstruments, setSelectorInstruments] = useState<Record<string, InstrumentSelectorInstrument>>({});
const InstrumentList = useMemo(() => {
        return Object.values(selectorInstruments).map((selectorInstrument: InstrumentSelectorInstrument) => (
            <SelectorInstrumentItem key={selectorInstrument.id} selectorInstrument={selectorInstrument}/>
            ))
      }, [selectorInstruments]);

Below is the List item using React.memo. I have tried setting the callback to check for prop changes, but the callback never even runs. I have console.logged() inside to verify that each item is rendering each time.

const SelectorInstrumentItem = React.memo(({selectorInstrument}: { selectorInstrument: InstrumentSelectorInstrument}) => {
        return <StyledMenuItem
        key={selectorInstrument.id}
        view={selectorInstrument.view}
        sx={{
            paddingX: 1.5, 
            borderRadius: 2,
        }}
        className='flex rounded-sm'
        onClick={(e: any) => {
            e.stopPropagation();
            handleDropdownItemEvent(e, selectorInstrument.id);
        }}

    >

  
    </StyledMenuItem>
      });

Below is how im updating selectedItems. It updates two of them, but as I said all 50 get rerendered

setSelectorInstruments(prevState => {
            const newState: Record<string, InstrumentSelectorInstrument> = {...prevState}
            
            const newInstrument = newState[instrumentId];
            if (newInstrument) {
                newState[instrumentId] = {
                    ...newInstrument,
                    view: instrumentInformation.view
                }
            }
            const prevInstrument = newState[oldPrimaryInstrument.instrument.id];
            if (prevInstrument) {
                newState[oldPrimaryInstrument.instrument.id] = {
                    ...prevInstrument,
                    view: oldPrimaryInstrument.view
                }
            }

            return newState;
            });

there is an associated function `from_str` with a similar name in Rust

i am using Rust as WSAM inside Angular app here is my cargo.toml i am looking to filter JSON and find the object by key

[package]
name = "my-rust-wasm"
version = "0.1.0"
edition = "2024"

[dependencies]
wasm-bindgen = "0.2"
regex = "1"
chrono = "0.4"
serde = { version = "1.0", features = ["derive"] }
serde-wasm-bindgen = "0.5"
serde_json = "1.0"


[lib]
crate-type = ["cdylib", "rlib"]

Now here is my lib.rus file

 #[wasm_bindgen]
 #[derive(Serialize, Deserialize)]
  pub struct Object {
   key: String,
   value: String,
 }

#[wasm_bindgen]
 pub fn find_object_by_key(arr: JsValue, target_key: &str) -> JsValue {
  let objects: Vec<Object> = arr.into_serde().unwrap_or_default();
  let result: Vec<Object> = objects
    .into_iter()
    .filter(|obj| obj.key == target_key)
    .collect();
  JsValue::from_serde(&result).unwrap()
}

And this is component.ts code

 let objects = [
    { key: "id1", value: "Object 1" },
    { key: "id2", value: "Object 2" },
    { key: "id3", value: "Object 3" },
  ];
  
  let targetKey = "id2";
  console.log(wasmModule.find_object_by_key(objects, targetKey)); // Expected Output: [{ key: "id2", value: "Object 2" }]

But i am getting this error there is an associated function from_str with a similar name
Error

Error 2

Transpose chords value doesn’t work normally in Javasript

I have 7 buttons, C D E F G A B , a textarea and an Original Key.

If I copy the lyrics “Fly me to the moon” into the textarea with its chords and press the E button once, it will go up a tone normally.
However, if I press the same button again, it will go up another tone.
What is wrong with the value, can someone explain to me?
Thank you in advance

const { transpose, Interval } = Tonal;

// Function to transpose chords in the text
function transposeChords(text, interval) {
return text.replace(/b([A-G][#b]?)(m|min|maj|dim|dim7|aug|sus|add)?([0-9]*)b/g, (match, root, type, number) => {
let chordType = type;

// Handle extended chords
if (number) {
chordType = chordType || '';
if (number.match(/d+/)) {
    chordType += number; 
}
}
    
try {
const  transposedRoot = transpose(root, interval);
const  transposedChord = transposedRoot + (chordType || '');
return transposedChord || match;
} catch (e) {
    console.error('Error transposing chord', match, e);
    return match;
}
});
}

// Function to handle transpose button click
window.transpose = function(padd) {
let interval = Interval.distance(window.originalKey, padd);
let lyrics = document.getElementById("textarea").value;
document.getElementById('textarea').value = transposeChords(lyrics, interval);
colorPads(padd);
};


//  Highlighted 17 Pads
function colorPads(padd) {
const buttons = document.querySelectorAll('.pads');
buttons.forEach(button => {
    if (button.dataset.padd === padd) {
        button.classList.add('blue');
    } else {
        button.classList.remove('blue');
    }
});
}


// Save original key when selected from dropdown
function originalKey_function() {
    const select_OrigKey = document.getElementById('originalKey_id');
    window.originalKey = select_OrigKey.value;
    colorPads(window.originalKey);
}


// Event listener for pads (17 buttons)
document.querySelectorAll('.pads').forEach(button => {
    button.addEventListener('click', () => {
    const padd = button.dataset.padd;
    window.transpose(padd);
    });
});

// Event listener for original key dropdown
document.getElementById('originalKey_id').addEventListener('change', originalKey_function);

// Initial setup
window.originalKey = 'C'; // Default original key
colorPads(window.originalKey);
body {
    font-family: Arial, sans-serif;
    background-color: #333;
    color: #ddd;
    text-align: center;
}

.pads_container {
    position:relative;
    top:2vmin;  
    display:flex;
    width:95%;
    left:1vmin;
    right:1vmin;
}

button.pads {
    padding: 1em;
    font-size: 3vmin;
    border: 1px solid #ccc;
    background: green;
    color: #fff;
    cursor: pointer;
}

button.pads.blue {
    background-color: #007bff;
    color: #fff;
}

button.pads:hover {
    background-color: #00a3d9;
}

#textarea {
    top:3em;
    position:relative;
    width:100%;
    background: #222;
    color: #ddd;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<script src="https://cdn.jsdelivr.net/npm/tonal/browser/tonal.min.js"></script>
<script>
  console.log(Tonal.Key.minorKey("Ab"));
</script>
</head>
<body>

<!-- Original Key -->
<div>
    <label for="originalKey_id">Original Key:</label>
    <select id="originalKey_id">
        <option value="C">C</option>
        <option value="D">D</option>
        <option value="E">E</option>
        <option value="F">F</option>
        <option value="G">G</option>
        <option value="A">A</option>
        <option value="B">B</option>
    </select>
</div>


<!-- 17 buttons -->
<div class="pads_container">
    <button class="pads" data-padd="C">C</button>
    <button class="pads" data-padd="D">D</button>
    <button class="pads" data-padd="E">E</button>
    <button class="pads" data-padd="F">F</button>
    <button class="pads" data-padd="G">G</button>
    <button class="pads" data-padd="A">A</button>
    <button class="pads" data-padd="B">B</button>
</div>




<textarea value="" id="textarea" rows="5" cols="25">
 D             G             A              D
Fly me to the moon, let me play among the stars
</textarea>
</div>



</body>
</html>

Besides Adobe Flash, are there any other drawing software options that can easily achieve the effects shown in the example?

imageExample

In Flash software, a vector graphic’s path and fill can be separated in this magical way, allowing for easy cutting of patterns, distorting boundaries or lines, and performing splices with just the black arrow tool (selection tool)… I cannot find any other software that can accomplish these same operations as effortlessly. In software like Photoshop and Illustrator, if one uses the pen tool to draw these elements, not only is the drawing process cumbersome, but their paths are closed, with strokes and fills connected together, making it extremely difficult to perform the same operations seen in the image… Currently, I feel that Flash (Animate CC) is the most user-friendly vector design software (?). At least for designers, Flash’s functionality allows ideas to be drawn out at the fastest speed… So, regarding the implementation of similar functionalities, are there any bottlenecks or technical difficulties in the software algorithms? Apart from Flash, I haven’t seen another piece of software use a simple tool (black arrow – selection tool) to so easily accomplish similar tasks.

Puppeteer with React – can’t fetch data (nextjs)

I have the following page on my website:

'use client';
import { useExam } from '@/api/exam/hooks';
import { Suspense } from 'react';

export default function ExamPdfPage({
  params: { id },
}: {
  params: { id: string };
}) {
  const { data: exam, isFetching, isSuccess } = useExam(id);

  if (isFetching) return <div>Loading</div>;
  if (!isSuccess) return <div>Error</div>;

  return (
    <Suspense>
      {/* <TextGradient>{getExamName(exam)}</TextGradient> */}
      <p className='pdf-ready'>Zadania!</p>
      {exam && <span>Pobrano!</span>}
    </Suspense>
  );
}

When I open it with my dev environment it works fine – hook loads the data and page is displayed. However, when I open it with my backend (nestjs) and puppeeter like this:

    const browser = await puppeteer.launch({ executablePath: puppeteer.executablePath('chrome'), headless: false });
    const page = await browser.newPage();
    await page.goto(`http://localhost:3000/pdf/exam/${id}`, { waitUntil: 'networkidle0' });
    await page.waitForSelector('.pdf-ready');

    const filePath = path.resolve(process.cwd(), 'public', 'pdfs', `exam-${id}.pdf`);
    fs.mkdirSync(path.dirname(filePath), { recursive: true });

    const pdf = await page.pdf({
      path: filePath,
      printBackground: true,
      format: 'A4',
    });

    await browser.close();

then the page opens but the request to my server is not sent and after loading state, the error div appeared. What am I doing wrong? The page is public so its not related to authentication.