how to use Custom input event primeng angular

I have an angular 16 project
I have a number input, which is validated using formControls
Because we use this input a lot, I have put it in a custom component to make my work easier.

I use primeng inputNumbers

The summary of my custom-input-number code is as follows

html file :

<span class="p-float-label w-100" [formGroup]="form">
  <p-inputNumber
    formControlName="number"
    [disabled]="disabled"
    (onInput)="onChange($event)"
    (onBlur)="onTouched()">
  </p-inputNumber>
  <label for="{{ id }}" class="custom-input-label">{{ label }}</label>
</span>

<small class="unselectable">
  {{textValidators}}
</small>

typescript file :

import { ChangeDetectorRef, Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core';
import { AbstractControl, ControlValueAccessor, FormControl, FormGroup, NG_VALIDATORS, NG_VALUE_ACCESSOR, ValidationErrors } from '@angular/forms';

@Component({
  selector: 'ngx-custom-input-number',
  templateUrl: './custom-input-number.component.html',
  styleUrls: ['./custom-input-number.component.scss'],
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(() => CustomInputNumberComponent),
      multi: true,
    },
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomInputNumberComponent),
      multi: true,
    },
  ],
})
export class CustomInputNumberComponent implements OnInit, ControlValueAccessor {

  form: FormGroup;
  ngModel;
  selectedData = null;
  selectedCountry;
  getValidators;
  textValidators: string = '';

  @Input() mode;
  @Input() label;

  onChange!: (value: string) => void;
  @Output() onBlur = new EventEmitter();

  constructor(private cdr: ChangeDetectorRef) {
    this.ngModel = this.setNgModel;
  }

  ngOnInit(): void {
    this.form = new FormGroup({
      number: new FormControl(this.setDefaultValue),
    });
  }

  onTouched() {
    this.onBlur.emit(this.form.get('number').value)
  }


  writeValue(val: any): void {
    if (val) {
      this.form.get('number').setValue(val, { emitEvent: false });
    } else {
      this.form.get('number').setValue(null);
    }
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
    this.form.get("number").valueChanges.subscribe(fn);
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  setDisabledState?(isDisabled: boolean): void {
    isDisabled
      ? this.form.disable()
      : this.form.enable();
  }

  validate(c: AbstractControl): ValidationErrors | null {...}

}

When I want to use this in another component, it is completely normal
I use it and give it formControlName
like this

  <form [formGroup]="form"
    <ngx-custom-input-number [label]="..." formControlName="number"> </ngx-custom-input-number>
  </form>

Now exactly my problem is when the input value goes to the server That
everything will be ruined The amount that goes to the server

number : {
    formattedValue : '423',
    originalEvent : { isTrusted : true},
    value : 4234
  }

I only want this value and not other things
And my problem is that I can’t change the whole project
I want to change the custom-component as much as possible so that the whole project doesn’t need to be changed

Note: I upgraded the project from angular12 to angular16 and this
problem was not present in angular12

How can I configure different HTTP headers for different routes in Next.js on the client side?

How can I configure different HTTP headers for different routes in Next.js on the client side?

I encountered CORS and SharedBuffer errors in my Next.js application. While I managed to resolve the issues by setting up appropriate headers using the following code, the solution only works when I reload the page. When I navigate between routes on the client side, I still encounter errors.

Specifically:

  • The CORS issue was resolved for the /convert-voice/:path* route.
  • The SharedBuffer error persists for the /my-ai-voices route. Both routes are client-side routes.

I implemented custom HTTP headers for different routes on the client side in my Next.js application. When I reload the page, both routes (/convert-voice/:path* and /my-ai-voices) function as expected, and the CORS and SharedBuffer errors are resolved as intended. However, when I navigate between routes without reloading the page, I encounter the CORS error for the /convert-voice/:path* route and the SharedBuffer error for the /my-ai-voices route. I expected that the configured headers would persist across route changes and prevent these errors from occurring during navigation.

`

import './src/env.mjs';
/** @type {import('next').NextConfig} */

const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'zingzang.s3.eu-west-2.amazonaws.com',
        pathname: '/musicGenerated/**',
      },
      {
        protocol: 'https',
        hostname: 'randomuser.me',
        pathname: '/api/portraits/**',
      },
      {
        protocol: 'https',
        hostname: 'cloudflare-ipfs.com',
        pathname: '/ipfs/**',
      },
      {
        protocol: 'https',
        hostname: 'avatars.githubusercontent.com',
        pathname: '/u/**',
      },
      {
        protocol: 'https',
        hostname: 'picsum.photos',
      },
      {
        protocol: 'https',
        hostname: 'flagcdn.com',
      },
      {
        protocol: 'https',
        hostname: 'utfs.io',
      },
      {
        protocol: 'https',
        hostname: 'images.unsplash.com',
      },
      {
        protocol: 'https',
        hostname: 's3.amazonaws.com',
        pathname: '/redqteam.com/isomorphic-furyroad/public/**',
      },
      {
        protocol: 'https',
        hostname: 'isomorphic-furyroad.s3.amazonaws.com',
      },
      {
        protocol: 'https',
        hostname: 'd2sfqo51tiwost.cloudfront.net',
      },
    ],
  },
  reactStrictMode: false,
  swcMinify: true,
  async headers() {
    return [
      {
        source: '/my-ai-voices',
        headers: [
          {
            key: 'Cross-Origin-Embedder-Policy',
            value: 'require-corp',
          },
          {
            key: 'Cross-Origin-Opener-Policy',
            value: 'same-origin',
          },
          { key: "Access-Control-Allow-Credentials", value: "true" },
          { key: "Access-Control-Allow-Origin", value: "*" },
        ],
      },
      {
        source: '/convert-voice/:path*',
        headers: [
          {
            key: 'Cross-Origin-Embedder-Policy',
            value: 'unsafe-none | require-corp | credentialless',
          },
          {
            key: 'Cross-Origin-Opener-Policy',
            value: 'same-origin',
          },
          { key: "Access-Control-Allow-Credentials", value: "true" },
          { key: "Access-Control-Allow-Origin", value: "*" },
        ],
      },
      {
        source: '/ffmpeg_core_dist/ffmpeg-core.js',
        headers: [
          {
            key: 'Cross-Origin-Embedder-Policy',
            value: 'require-corp',
          },
          {
            key: 'Cross-Origin-Opener-Policy',
            value: 'same-origin',
          },
          { key: "Access-Control-Allow-Credentials", value: "true" },
          { key: "Access-Control-Allow-Origin", value: "*" },
        ],
      },
    ];
  },
};

export default nextConfig;


Is it possible to prevent having multiple selectors when setting an event listener on a button with an image inside?

I have an image inside a button, and I want to listen to clicks on the button.
Since the listener is on the button, then when the click is done on the img, it won’t work:

document.addEventListener("click", (event) => {
  if (event.target.matches(".my-button")) {
    console.log('My button clicked')
  }
});
button {
  background: none;
  color: inherit;
  border: none;
  padding: 1em;
  font: inherit;
  cursor: pointer;
  outline: inherit;
  background-color: #4681f4;
  line-height: 0;
}
<button class="my-button">
  <img src="https://cdn-icons-png.flaticon.com/128/483/483054.png" width="40" height="40"/>
</button>

So I have to add a second selector for the inner img as well:

document.addEventListener("click", (event) => {
  if (event.target.matches(".my-button, .my-button img")) {
    console.log('My button clicked')
  }
});
button {
  background: none;
  color: inherit;
  border: none;
  padding: 1em;
  font: inherit;
  cursor: pointer;
  outline: inherit;
  background-color: #4681f4;
  line-height: 0;
}
<button class="my-button">
  <img src="https://cdn-icons-png.flaticon.com/128/483/483054.png" width="40" height="40"/>
</button>

But that feels redundant and as if I am doing something wrong.
Is there a way to avoid this? I was thinking at first to just use the img without a button element, but that feels like not according to the spec.

Event Date Input Displays Incorrect Date When Local Timezone Changed to US-based

When I change my local timezone to a US-based one, the event date does not work properly. It does not display the selected date in the event date input; instead, it displays the previous date. (For example: when I select 03-14-2024 in the input field, it displays 03-13-2024). Could someone please provide a solution to fix this issue, even when the local timezone changes?

HTML:

<input id="pickup-date-validate" class="form-control" type="datetime-local" data-date-format="YYYY-MM-DDThh:mm" onchange="formatDate('pickup-date-validate')" placeholder="Pickup date & Time" name="pickup_date" required>

<input id="return-date-validate" class="form-control" type="datetime-local" data-date-format="YYYY-MM-DDThh:mm"onchange="formatDate('return-date-validate')" placeholder="Return date & Time" name="return_date" required>

<input id="event-date-validate" class="form-control mt-xl-2 mt-lg-2 mt-md-0" type="date"
data-date-format="MM-DD-YYYY" onchange="formatDate('event-date-validate')" placeholder="Event date" name="event_date" required>

Script:

jQuery(document).ready(function ($) {
  // Initialize selectedPickUpDate and selectedReturnDate variables
  let selectedPickUpDate;
  let selectedReturnDate;
    
   // Function to format date using moment.js
   function formatMomentDate(date, format) {
     return date ? moment(date).format(format) : "";
   }
    
   // Pickup Date
        let pickUpDateSelect = document.getElementById("pickup-date-validate");
        if (pickUpDateSelect !== null) {
            // Set the minimum value for the input to the current date and time
            const pickUpNow = moment();
            pickUpDateSelect.min = formatMomentDate(pickUpNow, "YYYY-MM-DDTHH:mm");
    
            // Event listener for pickup date selection
            $(pickUpDateSelect).on("change input", function () {
                selectedPickUpDate = moment($(this).val());
    
                // Condition 1: When Pickup date is selected, set Return date minimum value
                let returnMinDate = moment(selectedPickUpDate).add(1, 'days');
                ReturnDateSelect.min = formatMomentDate(returnMinDate, "YYYY-MM-DDTHH:mm");
    
                // Update data-date attribute and format
                this.setAttribute("data-date", selectedPickUpDate ? selectedPickUpDate.format("MM-DD-YYYY HH:mm") : '');
                this.setAttribute("data-date-format", "MM-DD-YYYY HH:mm");
    
                // Update Event Date minimum value to allow selecting the pickup date
                EventDateSelect.min = formatMomentDate(selectedPickUpDate, "YYYY-MM-DD");
            });
        }
    
        // Return Date
        let ReturnDateSelect = document.getElementById("return-date-validate");
        if (ReturnDateSelect !== null) {
            // Event listener for return date selection
            $(ReturnDateSelect).on("change input", function () {
                selectedReturnDate = moment($(this).val());
    
                // Adjust Return date minimum value to prevent selecting the same date as the pickup date
                let adjustedReturnMinDate = moment(selectedPickUpDate).add(1, 'days');
                ReturnDateSelect.min = formatMomentDate(adjustedReturnMinDate, "YYYY-MM-DDTHH:mm");
    
                // Condition 2: When Return date is selected, set Event date minimum and maximum values
                let eventMinDate = moment(selectedPickUpDate);
                let eventMaxDate = moment(selectedReturnDate);
                EventDateSelect.min = formatMomentDate(eventMinDate, "YYYY-MM-DD");
                EventDateSelect.max = formatMomentDate(eventMaxDate, "YYYY-MM-DD");
    
                // Update data-date attribute and format
                this.setAttribute("data-date", selectedReturnDate ? selectedReturnDate.format("MM-DD-YYYY HH:mm") : '');
                this.setAttribute("data-date-format", "MM-DD-YYYY HH:mm");
            });
        }
    
        // Event Date
        let EventDateSelect = document.getElementById("event-date-validate");
        if (EventDateSelect !== null) {
            // Event listener for event date selection
            $(EventDateSelect).on("change input", function () {
                const selectedEventDate = moment($(this).val());
    
                // Disable pickup date and dates after return date in the event date selection
                if (selectedReturnDate && selectedEventDate.isAfter(selectedReturnDate)) {
                    $(this).val(""); // Clear event date
                }
            });
        }
    });

Environment: WordPress:6.4.3, moment.js, PHP:8.0.30

When the local timezone is changed to a US-based one and a date is selected in the event date input field, the displayed date should match the selected date accurately, without any discrepancies or shifts in time. For instance, if the user selects the date “03-14-2024”, the input field should display “03-14-2024” consistently, irrespective of any changes in the local timezone setting. This ensures that the displayed date remains synchronized with the user’s intended selection, regardless of timezone adjustments.

Why there is no built-in zip function in JavaScript?

I’m just curious why there isn’t any built-in zip function in javascript.

I’ve used a number of modern or older programming languages, such as python, kotlin, and rust. These days I’m writing codes in javascript and enjoying functional programming with it, since it provides built-in higher order functions such as filter, map, and reduce. At the same time it seems that the javascript community encourages functional programming.

However, I encountered a question: Why javascript does not provide zip function?

It is provided in many other programming languages and very useful and convenient when I need to work with multiple iterables in parallel. For example, in python:

numbers = [1, 2, 3]
upper = ["A", "B", "C"]
lower = ["a", "b", "c"]

for n, u, l in zip(numbers, upper, lower):
    print(f"{n}, {u}, {l}")

Of course the same result can be achieved in javascript, using map or forEach, or for loop.

const numbers = [1, 2, 3];
const upper = ["A", "B", "C"];
const lower = ["a", "b", "c"];

numbers.forEach((n, i) => {
    console.log(`${n}, ${upper[i]}, ${lower[i]}`);
});

It doesn’t look so neat for me, so I may write a custom zip function.
(btw, it won’t work correctly when iterables of different sizes are provided.)

function zip(...iterables) {
    return iterables[0].map((_, i) => iterables.map((it) => it[i]));
}

zip(numbers, upper, lower).forEach(([n, u, l]) => {
    console.log(`${n}, ${u}, ${l}`);
})

But I don’t want to write this everytime.
Neither to add any library for it.

So what’s the reason there’s no built-in one?

Javascript json customization

Hi here i am trying to manipulate one json file to below format. I am not able to think how to do that ?

The way i am thinking is not efficient thats why i need hep on this ?

Is there any easy way to do this.

Please have a look

[
 {
    "nid": "61629",
    "title": "K02 - Kiosk Slider - EN",
    "itemsSlider": [
      {
        "nid": "61626",
        "status": "1",
        "titleNode": "01Additional Suitcase - EN",
        "language": "en_US"
      },
      {
        "nid": "61626",
        "status": "1",
        "titleNode": "01Additional Suitcase - EN",
        "language": "en_US"
      }
    ]
  },
  {
    "nid": "61629",
    "title": "K02 - Kiosk Slider - EN",
    "itemsSlider": [
      {
        "nid": "61626",
        "status": "1",
        "titleNode": "01Additional Suitcase - EN",
        "language": "es_MX"
      },
      {
        "nid": "61626",
        "status": "1",
        "titleNode": "01Additional Suitcase - EN",
        "language": "es_MX"
      }
    ]
  },
  {
    "nid": "61629",
    "title": "K02 - Kiosk Slider - EN",
    "itemsSlider": [
      {
        "nid": "61626",
        "status": "1",
        "titleNode": "01Additional Suitcase - EN",
        "language": "fr_FR"
      },
      {
        "nid": "61626",
        "status": "1",
        "titleNode": "01Additional Suitcase - EN",
        "language": "fr_FR"
      }
    ]
  },
  {
    "nid": "61629",
    "title": "K02 - Kiosk Slider - Mix",
    "itemsSlider": [
      {
        "nid": "61626",
        "status": "1",
        "titleNode": "01Additional Suitcase - EN",
        "language": "es_MX"
      },
      {
        "nid": "61626",
        "status": "1",
        "titleNode": "01Additional Suitcase - EN",
        "language": "en_US"
      }
    ]
  }
]

THis this the output i am expecting for:
Please have a look Is there any way to achive it?

{
  "es_MX": [
    {
      "nid": "61626",
      "status": "1",
      "titleNode": "01Additional Suitcase - EN",
      "language": "es_MX"
    },
    {
      "nid": "61626",
      "status": "1",
      "titleNode": "01Additional Suitcase - EN",
      "language": "es_MX"
    }
  ],
  "fr_FR": [
    {
      "nid": "61626",
      "status": "1",
      "titleNode": "01Additional Suitcase - EN",
      "language": "fr_FR"
    },
    {
      "nid": "61626",
      "status": "1",
      "titleNode": "01Additional Suitcase - EN",
      "language": "fr_FR"
    }
  ]
}

How to check input between min & max number in react?

I have 2 costs min & max. I want when user type number in input manually then the user can only type number between min & max number. i want to do it in React/Next js.

<Input
    value={tripCoverage}
    onChange={(e) => {
        const value = e.target.value;
        const { minCost, maxCost } =
            studentPrice()?.tripCost || {};
        const result = Math.max(
            minCost,
            Math.min(maxCost, Number(value))
        );
        setTripCoverage(result);
    }}
    type="number"
/>

at the time of downloading files from s3 bucket one file is not able to download

anthi:_anti_hair_thinning_hair_spray.png
this the file name in s3 when it downloaded using s3 client it save file with name anthi and with 0kb also file type shows file , wherever in s3 it is 100kb and file type is png

I am using fs to save the file locally with same name please help me

 const objects = await s3.listObjectsV2(listParams).promise();
        for (const object of objects.Contents) {
            if (object.Size >= MIN_FILE_SIZE_IN_BYTES) {
                const fileKey = object.Key;
                const fileExtension = path.extname(fileKey).toLowerCase();
                if (allowedFileExtensions.includes(fileExtension)) {
                    const localFilePath = path.join(localDownloadFolder, path.basename(fileKey));
                    const data = await s3.getObject({ Bucket: bucketName, Key: fileKey }).promise();
                    fs.writeFileSync(localFilePath, data.Body);
                    // console.log(`File downloaded to: ${localFilePath}`);
                }
            }
        }

I will be very thankful for any suggestion or advice.

i tried to download files form asw s3 bucket

it is failing to download file name (anthi:_anti_hair_thinning_hair_spray.png ) with column

as using fs to write file in folder

how could i fix this?

Problems getting response of API request using Postman error { } [duplicate]

I created some documents in MongoDB that are Families, Users, Devices (https://i.stack.imgur.com/oeDU0.png)
What I’m trying to do is to display all devices within a specific family using the Id from http request. For example, http://localhost:8567/get?familyId=65f1dcc828d6b2d79bb2f4b4

Here is the models in VSCODE

My router:

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

// GET
router.get('/get', DevicesControl.getFamilyDevices);
module.exports = router;

My controller:

const mongoose = require('mongoose');
const Devices = require('../HomeModel/Devices');
const Families = require('../HomeModel/Families');
const ObjectId = mongoose.Types.ObjectId

const DevicesControl = {

    getFamilyDevices: async (req, res) => {
        try {
            console.log('GET request is active');
            const familyId = req.query.familyId;
            if (!familyId) {
                res.status(404).json('Family not found');
            }
            const foundFamily = await Families.findById(familyId);
            const devices = await foundFamily.devices()
            res.status(200).json(devices)
;
        }
        catch (error) 
        {
           res.status(500).json({ error: 'Error getting Devices', details: error });
        }
    }
};
module.exports = DevicesControl;     

The { } error in Postman here

I tried with simply returning the familyId from the request and it worked just fine. However, when it comes to returning documents everything is different.
I’m hoping the correct response should return the devices in ‘Devices’ model (https://i.stack.imgur.com/6EaSw.png)

I looked at some resources, perhaps the error representa empty object. I’m super new to this stuff and can’t solve it myself. Please help me figure out what’s going wrong with that error and how to fix it.

Data table refresh and pagination

i’m working on a simple crud data table, i add refresh function without reloading the page using ajax to append html. it works fine, then there’s conflict when i add pagination from laravel. the table only shows the first 5 data from fetched data on the next page.

$(document).ready(function() {
  // Function to refresh table data
  function refreshTable(page) {
      $.ajax({
          url: '/get-latest-projects?page=' + page, // URL to fetch updated data
          method: 'GET',
          success: function(response) {
              // Update table with new data
              $('#dataTable tbody').html(' '); // Assuming data is HTML for the table body only

              $.each(response.data, function(index, item) {
                var row = '<tr class="tr">';
                row += '<td>' + item.input_date + '</td>';
                row += '<td>' + item.nama_project + '</td>';
                row += '<td class="desc">' + item.requestor + '</td>';
                row += '<td>' + item.category_project + '</td>';
                row += '<td><span>' + item.description_project + '</span></td>';
                row += '<td>' + item.status + '</td>';
                row += '<td><span class="status--process">' + item.pic_project + '</span></td>';
                row += '<td>' + item.eta_project + '</td>';
                row += '<td><div class="table-data-feature" id="editContainer">';
                row += '<button type="button" class="item" data-toggle="modal" data-target="#editModal' + item.id + '" data-placement="top" title="Edit"><i class="zmdi zmdi-edit"></i></button>';
                row += '<button class="item" data-toggle="tooltip" data-placement="top" title="Delete"><i class="zmdi zmdi-delete"></i></button>';
                row += '</div></td></tr>';
                $('#dataTable tbody').append(row);
            });
          },
          error: function(xhr, status, error) {
              console.error('Error refreshing table:', error);
          }
      });
  }

  refreshTable(1);

  // Reload table when the button is clicked
  $('#reloadButton').click(function() {
      refreshTable(1);
  });
});

the table is able to show the next data on next page only for a blink then covered by appended html which containing new data fetched

    public function index()
    {
        $projects = Project::orderBy('id', 'desc')->paginate(5);
        return view('table', compact('projects'));

    }


    
    public function getLatestProjects()
    {
        $projects = Project::orderBy('id', 'desc')->latest()->paginate(5); // Adjust as needed
        return response()->json($projects);
    }

this is another try from before which the object wasn’t defined.

How to use signalr invoke a function from server side to cancel the upload progress?

Signalr backend controller setup:

namespace Antz.App.SignalR.Hubs
{
    public class ProgressHub : Hub
    {
        public static bool IsCancelled = false;

        public void SendProgress(string progressMessage, int progressCount, int totalItems)
        {
            //Thread.Sleep(1);
            var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();
            var percentage = (progressCount * 100) / totalItems;
            hubContext.Clients.All.AddProgress(progressMessage, percentage + "%");
        }

        public void IsCancelledUpload()
        {
            IsCancelled = true;
        }
    }
}

Javscript:

signalrConnection = $.hubConnection("/SignalR", { useDefaultPath: false });
signalrProxy = signalrConnection.createHubProxy('ProgressHub');

signalrProxy.on('AddProgress', function (message, percentage) {

    UpdateProgressBar(percentage);

});

/* signalrConnection.logging = true;*/

signalrConnection.start({ transport: 'longPolling' }).then(function () {

    console.log("Connection Started");

});

signalrConnection.disconnected(function () {
    console.log('Disconnected');

    setTimeout(function () {
        signalrConnection.start({ transport: 'longPolling' }).then(function () {
            console.log("Connection Started");
        });
    }, 3000);
});

signalrConnection.error(function (error) {
    console.log(error);
});

function UpdateProgressBar(percentage) {

    const progressBar = document.querySelector(".progress-bar");
    progressBar.style.opacity = "1";
    progressBar.style.width = percentage;
    progressBar.innerHTML = percentage;

    if (percentage === "100%") {

        progressBar.style.width = "";
        progressBar.innerHTML = "";

    }
}

Upload function backend controller:

ProgressHub progressHub = new ProgressHub();

var refNoList = new List<string>();
await Task.Run(async () =>
{
    foreach (ArrayList row in data3)
    {
        recordProcessed++;

        rowIndex++;
        // skip row 1 as it's a header
        if (rowIndex == 1)
        {
            continue;
        }

        progressHub.SendProgress("Process in progress...", rowIndex, totalRows);
        //await Task.Delay(5000); // Introduce a small delay

        bool all_pass = true;

        string docType = row[0].ToString().Trim();
        string refNo = row[1].ToString().Trim();
        string vendor = row[2].ToString().Trim();
        string remark = row[3].ToString().Trim();

I’ve tried to put a static field on the class ProgressHub and if the user was clicked the cancel button, the button will trigger the signalr to invoke the function IsCancelledUpload which is use to update the IsCancelled boolean to true. So Excel upload function will check if the boolean is true, the loop will be break. But using static is not a wise choice, so I’m seeking another approach for this.

how seTimeout() executing continuously?

Since we know that setTimeout() function execute only once then how the following program executing continuously:

import {useState} from "react"

const App = () => {

        const [counter, setcounter] = useState(0);

        setTimeout( () => setcounter (counter+1), 1000)
        

        return (
          <div>{counter} </div>
        )

}

export default App

please anybody can identify it? which code piece triggering the setTimeout() to execute continuously?

how to use buttons with the onClick method in the latest nextJS version 14.1.3

"use client"
import React, { useState } from "react";
import { FaChevronLeft, FaChevronRight } from "react-icons/fa";

export default function HeroSlider() {
  const images = [
    "/images/homepage/home-1.jpeg",
    "/images/homepage/home-2.jpg",
    "/images/homepage/home-3.jpg",
    "/images/homepage/home-4.jpg",
    "/images/homepage/home-5.jpg",
    "/images/homepage/home-6.jpg",
    "/images/homepage/home-7.jpg",
  ];
  const [currentImageIndex, setCurrentImageIndex] = useState(0);

  const nextImage = () => {
    setCurrentImageIndex((nextIndex) =>
    nextIndex === images.length - 1 ? 0 : nextIndex + 1
    );
  };

  const prevImage = () => {
    setCurrentImageIndex((prevIndex) =>
      prevIndex === 0 ? images.length - 1 : prevIndex - 1
    );
  };

  return (
    <div>
      <div style={{ position: "relative", width: "100%", height: "auto" }}>
        <img
          src={images[currentImageIndex]}
          alt="Your Image"
          style={{ width: "100%", height: "auto", objectFit: "cover" }}
        />
        <div
          style={{
            width: "5%",
            position: "absolute",
            top: "50%",
            left: "0",
            transform: "translateY(-50%)",
            zIndex: 1,
          }}
        >
          <button
            type="button"
            onClick={prevImage}
            className="absolute top-1/2 left-0 transform -translate-y-1/2 bg-transparent border-none"
          >
            <FaChevronLeft size={40} color="white" />
          </button>
        </div>
        <div
          style={{
            width: "5%",
            position: "absolute",
            top: "50%",
            right: "0",
            transform: "translateY(-50%)",
            zIndex: 1,
          }}
        >
          <button
            type="button"
            onClick={nextImage}
            className="absolute top-1/2 right-0 transform -translate-y-1/2 bg-transparent border-none"
          >
            <FaChevronRight size={40} color="white" />
          </button>
        </div>
      </div>
    </div>
  );
}

why do the nextImage and prevImage functions not work?

I’m making a slider hero component, so I applied the use state concept, and created the nextImage and prevImage functions to change the useState value via the button with the onClick method, but why isn’t that function called? Can anyone help me here?