JS How to remove item from arr2 but keep refference to arr2?

what i want to get?

let arr2=['aa','bb','cc','dd'];
let arr3=arr2;
arr2.remove('bb');
console.log(arr2);//['aa','cc','dd'];
console.log(arr3);//['aa','cc','dd'];
arr3.remove('aa');//['cc','dd'];
console.log(arr2);//['cc','dd'];
console.log(arr3);//['cc','dd'];

here is my first thoughts about how to get:
first:
find index of item
second
switch position

let index=arr2.findIndex(item);
arr2[index]=arr2.at(-1);
arr2.pop();
//switch last one and ele of index

How to use react-hook-form with react context?

I am trying to use react-hook-form with react context, but the form is not behaving as intended.
problems what I am facing

  1. on submission error states are not triggered.
  2. using watch() and monitoring changes, I see that it inputs are not controlled and I can’t see the changes.
  3. values like isDirty, isSubmitSuccessful doesn’t change from the initial state.

I then moved useForm out of context and directly consumed it inside the component where the form is created, and everything works just fine.
I wanted to know if anyone is aware of why is this the case? Can’t we use react-hook-form in side a context provider?

below is my attached code for context.

import { zodResolver } from '@hookform/resolvers/zod';
import { createContext, ReactNode, useContext } from 'react';
import { useForm, UseFormReturn } from 'react-hook-form';
import { z } from 'zod';

import { CompanyTypeEnum } from '@/types/buyer.type';
import { CountrySchema, PhoneSchema } from '@/types/common.type';

type BuyerFormContext = UseFormReturn<BuyerForm>;

const BuyerFormContext = createContext<BuyerFormContext | undefined>(undefined);

const BuyerFormSchema = z.object({
  id: z.string().uuid().optional(),
  companyName: z.string().min(1),
  companyType: CompanyTypeEnum,
  companyPhone: PhoneSchema,
  streetLine1: z.string().min(1),
  streetLine2: z.string().optional(),
  city: z.string().min(1),
  stateOrRegion: z.string().min(1),
  postalCode: z.string().min(1),
  country: CountrySchema,
  website: z.string().min(1),
  defaultCurrency: z.string(),
  contactName: z.string().min(1),
  contactPosition: z.string().min(1),
  contactPhone: PhoneSchema,
  contactEmail: z.string().email(),
});

export type BuyerForm = z.infer<typeof BuyerFormSchema>;

export const BuyerFormProvider = ({
  children,
  defaultValues,
}: {
  children: ReactNode;
  defaultValues?: BuyerForm;
}) => {
  const form = useForm<BuyerForm>({
    resolver: zodResolver(BuyerFormSchema),
    mode: 'onSubmit',
    defaultValues: formDefault,
  });

  return <BuyerFormContext.Provider value={form}>{children}</BuyerFormContext.Provider>;
};

export const useBuyerForm = () => {
  const context = useContext(BuyerFormContext);
  if (context === undefined) {
    throw new Error('useBuyerForm must be used within a BuyerFormProvider');
  }
  return context;
};

my usage is as below

import { Loader2 } from 'lucide-react';
import { SubmitHandler } from 'react-hook-form';
import { useBlocker } from 'react-router-dom';

import { CustomSelect as CompanyTypeSelect } from '@/components/custom-select';
import { CustomSelect as ContactPositionSelect } from '@/components/custom-select';
import { Button } from '@/components/ui/button';
import { CountryDropdown } from '@/components/ui/country-dropdown';
import { CurrencySelect } from '@/components/ui/currency-select';
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { PhoneInput } from '@/components/ui/phone-input';
import { Separator } from '@/components/ui/separator';
import { type BuyerForm, useBuyerForm } from '@/context/buyer-form-context';
import { CURRENCIES } from '@/service/types';
import { COMPANY_TYPES } from '@/types/buyer.type';
import { CONTACT_POSITIONS, Country } from '@/types/common.type';

const BuyerForm = (props: {
  onCancel: () => void;
  onSubmit: SubmitHandler<BuyerForm>;
  formTitle?: string;
  submitBtnText?: string;
  isFormLoading?: boolean;
  isEdit?: boolean;
}) => {
  const {
    onCancel,
    onSubmit,
    formTitle = 'Edit Buyer',
    submitBtnText = 'Save Changes',
    isFormLoading = false,
    isEdit = false,
  } = props;

  const form = useBuyerForm(); // Assuming you are using useForm from react-hook-form
  const {
    formState: { isDirty, isSubmitSuccessful },
  } = form;

  useBlocker(({ currentLocation, nextLocation }) => {
    if (!isSubmitSuccessful && isDirty && currentLocation.pathname !== nextLocation.pathname) {
      return !window.confirm('You have unsaved changes. Are you sure you want to leave?');
    }
    return false;
  });

  const onCountryChange = (country: Country) => {
    const formValues = form.getValues();

    if (!isEdit) {
      if (!form.getFieldState('defaultCurrency').isTouched || formValues.defaultCurrency === '') {
        const countryCurrency = country.currencies[0];
        if ((CURRENCIES as string[]).includes(countryCurrency)) {
          form.setValue('defaultCurrency', countryCurrency);
        }
      }

      if (!form.getFieldState('companyPhone').isTouched || formValues.companyPhone.phone === '') {
        form.setValue('companyPhone', {
          phone: country.countryCallingCodes[0],
          country: country,
        });
      }
    }
  };

  return (
    <div className='mt-10'>
      <h1 className='h1 lg:mx-auto lg:max-w-screen-md'>{formTitle}</h1>
      <Form {...form}>
        <form
          className='mt-5 pb-20 lg:mx-auto lg:max-w-screen-md'
          onSubmit={form.handleSubmit(onSubmit)}>
          <div className='flex flex-col justify-between gap-y-2'>
            <div className='flex justify-between gap-x-4'>
              <FormField
                control={form.control}
                name='companyName'
                render={({ field }) => (
                  <FormItem className='flex-1'>
                    <FormLabel>Company Name</FormLabel>
                    <FormControl>
                      <Input placeholder='Acme Inc.' {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name='companyType'
                render={({ field }) => (
                  <FormItem className='flex-1'>
                    <FormLabel>Company Type</FormLabel>
                    <FormControl>
                      <CompanyTypeSelect
                        onValueChange={field.onChange}
                        value={field.value}
                        name={field.name}
                        ref={field.ref}
                        options={COMPANY_TYPES}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <div className='flex gap-x-4'>
              <FormField
                control={form.control}
                name='companyPhone'
                render={({ field }) => (
                  <FormItem className='flex-1'>
                    <FormLabel>Company Phone</FormLabel>
                    <FormControl>
                      <FormControl>
                        <PhoneInput
                          {...field}
                          onChange={e => {
                            field.onChange({
                              phone: e.target.value.phone,
                              country: e.target.value.country,
                            });
                          }}
                          value={field.value.phone}
                          placeholder='Enter your number'
                          defaultCountry={field.value.country?.alpha2}
                          className='h-10'
                        />
                      </FormControl>
                    </FormControl>
                    <FormDescription>Include country code (e.g. +44)</FormDescription>
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name='website'
                render={({ field }) => (
                  <FormItem className='flex-1'>
                    <FormLabel>Website</FormLabel>
                    <FormControl>
                      <Input placeholder='https://example.com' {...field} className='flex-1' />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </div>
          <Separator className='my-4 h-px bg-gray-200' />
          <div className='space-y-2'>
            <h3 className='paragraph-l-bold text-gray-700'>Address</h3>
            <div className='space-y-2'>
              <div className='flex justify-between gap-x-4'>
                <FormField
                  control={form.control}
                  name='streetLine1'
                  render={({ field }) => (
                    <FormItem className='flex-1'>
                      <FormLabel>Street Line 1</FormLabel>
                      <FormControl>
                        <Input placeholder='e.g., 123 Main Street, Building A' {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name='streetLine2'
                  render={({ field }) => (
                    <FormItem className='flex-1'>
                      <FormLabel>
                        Street Line 2 <span className='paragraph-sm text-gray-400'>(optional)</span>
                      </FormLabel>
                      <FormControl>
                        <Input placeholder='e.g., Suite 100, Floor 3' {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
              <div className='flex justify-between gap-x-4'>
                <FormField
                  control={form.control}
                  name='postalCode'
                  render={({ field }) => (
                    <FormItem className='flex-1'>
                      <FormLabel>Postal Code</FormLabel>
                      <FormControl>
                        <Input placeholder='e.g., 94105' {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name='city'
                  render={({ field }) => (
                    <FormItem className='flex-1'>
                      <FormLabel>City</FormLabel>
                      <FormControl>
                        <Input placeholder='e.g., San Francisco' {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
              <div className='flex justify-between gap-x-4'>
                <FormField
                  control={form.control}
                  name='stateOrRegion'
                  render={({ field }) => (
                    <FormItem className='w-[calc(50%-8px)]'>
                      <FormLabel>State/Region</FormLabel>
                      <FormControl>
                        <Input placeholder='e.g., California' {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name='country'
                  render={({ field }) => (
                    <FormItem className='w-[calc(50%-8px)]'>
                      <FormLabel>Country</FormLabel>
                      <FormControl>
                        <CountryDropdown
                          placeholder='Select a country'
                          defaultValue={field.value.alpha3}
                          onChange={country => {
                            field.onChange(country);
                            onCountryChange(country);
                          }}
                          ref={field.ref}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>
          </div>
          <Separator className='my-4 h-px bg-gray-200' />
          <div className='space-y-2'>
            <h3 className='paragraph-l-bold text-gray-700'>Contact Person</h3>
            <div className='flex justify-between gap-x-4'>
              <FormField
                control={form.control}
                name={`contactName`}
                render={({ field }) => (
                  <FormItem className='flex-1'>
                    <FormLabel>Name</FormLabel>
                    <FormControl>
                      <Input placeholder='e.g., John Smith' {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name={`contactPosition`}
                render={({ field }) => (
                  <FormItem className='flex-1'>
                    <FormLabel>Position</FormLabel>
                    <FormControl>
                      <ContactPositionSelect
                        onValueChange={field.onChange}
                        value={field.value}
                        name={field.name}
                        ref={field.ref}
                        options={CONTACT_POSITIONS}
                        placeholder='Select a position'
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <div className='flex justify-between gap-x-4'>
              <FormField
                control={form.control}
                name={`contactEmail`}
                render={({ field }) => (
                  <FormItem className='flex-1'>
                    <FormLabel>Email</FormLabel>
                    <FormControl>
                      <Input placeholder='e.g., [email protected]' {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name={`contactPhone`}
                render={({ field }) => (
                  <FormItem className='flex-1'>
                    <FormLabel>Phone</FormLabel>
                    <FormControl>
                      <div className='flex w-full items-center'>
                        <CountryDropdown
                          onChange={country => {
                            const countryCode = country.countryCallingCodes[0];
                            const formattedCode = countryCode.startsWith('+')
                              ? countryCode
                              : `+${countryCode}`;
                            form.setValue(`contactPhone`, {
                              phone: formattedCode,
                              country: country,
                            });
                          }}
                          defaultValue={field.value.country?.alpha3}
                          inline
                        />
                        <PhoneInput
                          {...field}
                          onChange={e => {
                            field.onChange({
                              phone: e.target.value.phone,
                              country: e.target.value.country,
                            });
                          }}
                          value={field.value.phone}
                          placeholder='Enter your number'
                          defaultCountry={field.value.country?.alpha2}
                          inline
                        />
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </div>
          <Separator className='my-4 h-px bg-gray-200' />
          <div className='space-y-2'>
            <FormField
              control={form.control}
              name={`defaultCurrency`}
              render={({ field }) => (
                <FormItem className='w-[calc(50%-8px)]'>
                  <FormLabel>Payment Currency</FormLabel>
                  <FormControl>
                    <CurrencySelect
                      onValueChange={field.onChange}
                      placeholder='Select a currency'
                      disabled={false}
                      defaultValue={field.value}
                      currencies='all'
                      variant='default'
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
          <div className='fixed inset-x-0 bottom-0 border-t border-gray-200 bg-white/70 backdrop-blur-sm'>
            <div className='flex justify-end gap-x-4 py-4 lg:mx-auto lg:max-w-screen-md'>
              <Button variant='outline' onClick={onCancel} disabled={isFormLoading}>
                Cancel
              </Button>
              <Button type='submit' variant='flume' disabled={isFormLoading}>
                {isFormLoading && <Loader2 className='mr-2 size-4 animate-spin' />}
                <span>{submitBtnText}</span>
              </Button>
            </div>
          </div>
        </form>
      </Form>
    </div>
  );
};

export default BuyerForm;

How to generate vertex normals from gltf positions attribute buffer?

I`m trying to implement vertex normal generation from vertex positions using the cross product method (in javaScript, from a gltf positions buffer), but most of resulting normals turn out to be (0, 0, 0). Code:

        const vertices = new Float32Array(
            positionsBuffer,
            meshData.positions.byteOffset,
            meshData.positions.byteLength
        )

        const indices =
            new Uint16Array(
                indexBuffer,
                meshData.indices.byteOffset,
                meshData.indices.byteLength
            )

        const normals = new Float32Array(vertices.length)

        for (let i = 0; i < indices.length; i += 9) {
            const vert0 = vec3.create(
                vertices[indices[i]],
                vertices[indices[i + 1]],
                vertices[indices[i + 2]]
            )
            const vert1 = vec3.create(
                vertices[indices[i + 3]],
                vertices[indices[i + 4]],
                vertices[indices[i + 5]]
            )

            const vert2 = vec3.create(
                vertices[indices[i + 6]],
                vertices[indices[i + 7]],
                vertices[indices[i + 8]]
            )

            // p = cross(B-A, C-A)
            const normal = vec3.normalize(
                vec3.cross(
                    vec3.subtract(vert1, vert0),
                    vec3.subtract(vert2, vert0)
                )
            )

            normals[indices[i]] += normal[0]
            normals[indices[i + 1]] += normal[1]
            normals[indices[i + 2]] += normal[2]

            normals[indices[i + 3]] += normal[0]
            normals[indices[i + 4]] += normal[1]
            normals[indices[i + 5]] += normal[2]

            normals[indices[i + 6]] += normal[0]
            normals[indices[i + 7]] += normal[1]
            normals[indices[i + 8]] += normal[2]
        }

        for (let i = 0; i < indices.length; i += 3) {
            const normalizedNormal = vec3.normalize(
                vec3.create(
                    normals[indices[i]],
                    normals[indices[i + 1]],
                    normals[indices[i + 2]]
                )
            )

            normals[indices[i]] = normalizedNormal[0]
            normals[indices[i + 1]] = normalizedNormal[1]
            normals[indices[i + 2]] = normalizedNormal[2]
        }

What i expected to get is something similar to this image, but what i actually get now is this

I tried changing the winding order, to no effect. Normalizing or not also seems to make no difference (but that is due to normals being normalized in the shader anyway).
From what i have seen on the internet, the math seems to be fine.
I`m also rather confident that all vertices are processed, because tangents i generate in the same manner, turn out just fine. To me that means that normals[indices[i]] += normal[0] regularly produces 0, but i can not understand why. And what to do about it, if that is the problem. Any suggestions would be much appreciated.

FYI: rendering is done with webGPU, shader code doesn`t differ for either normals. Model is generated with Khronos Blender glTF 2.0 exporter

How can I efficiently copy the entries from one Map to another Map where the target Map has multiple reference variables?

I have found a way to copy the entries from one Map to another Map where the target Map has multiple reference variables but I suspect it is not optimal. Is there a shorter/more efficient way?

const mapFrom = new Map([[1, 'from']]);
const mapTo = new Map([[1, 'to']]);
const refMapTo = mapTo;
mapTo.clear();
for (const [key, value] of mapFrom) mapTo.set(key, value);
if (mapTo.get(1) === mapFrom.get(1) && mapTo === refMapTo) {
  console.log('this code works but can I avoid the `for...of` iteration?');
}

Indian Rupee (₹) Symbol Not Rendering Properly in jsPDF

enter image description hereI’m using jsPDF to generate invoices in my JavaScript project. Everything works fine when using the Dollar ($) symbol, but when I use the Indian Rupee (₹) symbol, the PDF output contains corrupted or missing characters.

Issue:

  1. The symbol does not appear correctly in the generated PDF.
  2. Instead, I see garbled text or missing characters.
  3. If I change to $, everything works fine.

How to open modal located in child component from parent when button clicked?

Parent has a button. When button is clicked how can we let the Child component know to open the modal?

Parent.vue

<script setup>
import Child from "Child.vue";
</script>

<template>
  <button onClick=""> // open modal when button clicked
  <Child/>
</template>    

Child.vue

<script setup>
import { ref } from "vue";

const openModal = ref(false);
</script>

<template>
  <div>example</div>
</template>

Next js Routing – Params are being enumerated

I’m using Next JS with dependency
“next”: “15.1.4”,
“react”: “^19.0.0”,
“react-dom”: “^19.0.0”,
I’m able to see output in browser, but error is showing as –
params are being enumerated. paramsshould be unwrapped withReact.use()before using its value. The keys ofsearchParamswere accessed directly.searchParamsshould be unwrapped withReact.use()` before accessing its properties.

Is serverless PWA possible?

I’m new to PWAs and I don’t really get it, I figured out how to get it to work offline with service worker cache, butt that still requires a server and I’d like it to be a completely offline thing, is that possible?

Ew resizing rotated rectange in html canvas

I’m trying to resizing a rotated rectangle in html canvas. The direction of resizing is ew resizing, so basically, the rectangle width must grow, while it mantains the height fixed.

I achieved to do it in the nwse resize in the example below. I understand how I achieve it, but I’m not being able to achieve in the ew resize.

In this example below, on the method adjust, in where I trying to handle this.

https://svelte.dev/playground/558adc2e7ed94682b06d1ff144a44ba2?version=5.19.6

How can you read modified class properties from another classes callback in javascript?

I have 2 classes with websockets. They should be used to send information from one to the other with the program as the intermediary. The WSS listens and can only have a single connection. I have a client connection with a different server. In my main function I instantiate each of these objects and assign forwardMessage(event) as a callback (onmessage) to the listener. It should essentially forward the contents but the problem is even after a client has connected to the serverWSS object, the callback always reports activeWS as null. I am not sure how I can get a reference of this between the two in this way.

class WSS {
    constructor(){
        const WebSocket = require('ws');
        this.wss = new WebSocket.Server({ port: 3001});
        this.activeWs = null;

        this.wss.on('connection', function connection(ws) {
            console.log("Client Connected");
            if (this.activeWs != null) {
                this.activeWs.close(1000, "Server initiated close");
                console.log("Closed old session")
            }
            this.activeWs = ws;
        })

        this.sendCommand = (data) => {
            console.log(this.activeWs)
            if (this.activeWs == null) {
                return;
            }
            console.log(data);
        }
    }
}

class WS {
    constructor(clientId, onmessage) {
        this.clientId = clientId;
        const WebSocket = require('ws');
        this.ws = new WebSocket('localhost:8080');
        this.ws.onmessage = (event) => { onmessage(event)};
    }
}

serverWSS = new WSS();
listener = new WS("000", forwardMessage)

function forwardMessage(event) {
    serverWSS.sendCommand(event.data);
}

Finding & Cropping to focused subject

I’m currently trying to find a method to find the subject (the character) of an sprite, preferably with JS.

enter image description here

Originally I thought of finding the part of the image with the most pixel density, though I’d assume issues would arise for characters with large weapons. I’ve tried looking around for solutions and the general conception seems to resort to some sort of recognition, like AI. If possible I’d like to avoid using AI. The solution doesn’t need to be real time either, the original images can be cropped beforehand.

Here is an example of the desired effects I’m looking for:
enter image description here

Any ideas or a point in the right direction will be greatly appreciated. I apologize in advance for not being able provide any code, as I’m yet unclear which direction to head.

How do I make a paragraph appear when there’s a “content” element in the div’s styles?

I’m making a portfolio page for my designs and I put the creations into multiple divs that are made using a function in javascript. All the images and styles are done but there’s one thing missing. I have made a label for every creation and I want it so that label slides up from the bottom of the div when I hover on it. I have tried using

but this interrupts the “Content” element in the div’s styles. Here’s the code:

Css:

#creationsCont {
width: 100%;
display: flex;
justify-content: center;
height: 250px;
flex-wrap: wrap;
}
#creationsCont div {
object-fit: contain;
padding: 5px;
width: 400px;
height: 250px;
margin-right: 10px;
margin-left: 10px;
border-radius: 15px;
margin-bottom: 10px;
border-color: #616161;
border-width: 2px;
border-style: solid;
box-sizing: border-box;
background-color: rgb(21, 12, 31);
flex-shrink: 0;

}

Html:

    <div id="creationsCont"></div>
<script src="loader.js"></script>

Javascript:

function newCreation(img, label) {
const creation = document.createElement("div");
creation.style.content = "url(Media/Creations/" + img; + ")"
document.getElementById("creationsCont").appendChild(creation);
}

Problem inserting digits in plain input field using Selenium Basic and JavaScript

The web page https://www7.skatteverket.se/portal/rakna-ut-skatt (by the Swedish tax authority and in Swedish) is used to figure out how much Swedish tax to pay.

For your info, the web page seems to be constructed using some Vue framework and also contains a lot of nested shadow roots that can be seen in the DOM, using the browsers developer tool and looking in the Element tab.

To figure out how much tax to pay, you need to input a lot of background info into input fields. These input field could be radio buttons or combo boxes, drop-down inputs or plan text inputs, normally in the form of digits. Also other buttons like ’next’ buttons or ’expand’ buttons to expose more input fields are quite common.

The web page is designed to manually input this background info by a person.

But instead I want to input all the background information programmatically from info in an excel sheet, using technics like VBA, JavaScript and Selenium Basic.

For the most part this already works very well. But I have a specific problem when programmatically entering text (digits) into a plain input field.

The problem occur when the current section of the web page contains such a text input fields and after text is input in it, and all other kind of fields, one should hit a ’next’ button to get to the next section of the web page, with normally more different kind of input fields.

It works using VBA, JavaScript and Selenium to input the text (digits) into the plain input field and the programmatically inputted value is shown on the web page.

But when hitting the ’next’ button to come to the web page’s next section, the text inputted into the plain input field disappear and an error message is shown telling you that you need to input value into the input field.

This error only occur for plain input fields and not for drop-downs or combo boxes.

If you in this situation manually input the same value into the input field, as previously has been programmatically inputted and displayed, the error disappears and the next section of the web page is displayed when you also hit the ’next’ button.

So the internal code in the web page somehow makes a difference when the same value is inputted into a plain input field manually or programmatically.

I have guessed, but I’m not sure, that this problem can be because different event listeners are triggered in the two situations. Therefore I have investigated using the browsers developer tool what event listeners are present on the input fields and also on its ancestors.

The input field where the problem is has three standard event listeners with the event type focus, change and blur.

To understand and log what event listeners are triggered and in what order, I have overridden the original dispatchEvent method, using the JavaScript code below.


// Save the original dispatchEvent method
const originalDispatchEvent = EventTarget.prototype.dispatchEvent;

// Override dispatchEvent
EventTarget.prototype.dispatchEvent = function (event) {
        // Log which event type was fired
        console.log(`Event type fired: ${event.type}`);

        // Log the element that triggered the event
        console.log("Event target:", event.target);

        // Log the dispatched event
        console.log("Event dispatched:", event);

        // If the event has a 'detail' property, log it
        if (event.detail) {
            console.log("Event detail:", event.detail);
        }
    
    // Call the original dispatchEvent method
    return originalDispatchEvent.call(this, event);
};

Focusing on the input field in question when entering values (digits) into it manually only the change event is triggered.

When the same input field was programmatically filled with digits the following event listernas was dispatched: focus, input, change and blur, using the following code:


actionNode.focus(); // Step 1: Focus
actionNode.value = actionCont; // Step 2: Set
actionNode.dispatchEvent(new Event('input', { bubbles: true })); // Step 3: Trigger input
actionNode.dispatchEvent(new Event('change', { bubbles: true })); // Step 4: Trigger change
actionNode.blur(); // Step 5: Remove focus

Nothing of this made the problem go away. The digits that is programmatically inserted into the input field and displayed on the web page, still disappear when the ’next’ button is hit.

I need some serious help to fix this situation.

My component does not re-render the contents of

I am trying to create a hook in my application made on Create React App, but when updating the constant that contains the information, the component that shows the list on the screen is not rendered again, but the list is updated, since the hook returns it updated in console (it is worth mentioning that when loading the component for the first time, it is rendered correctly, but it is not updated when the information changes).

Sales List

import React, { use, useState, useEffect } from 'react';
import { Table } from 'antd';
import UpdateList from '../hooks/updateList';

const SalesList = () => {
    const { list, loading, error, updateList } = UpdateList();

    useEffect(() => {
        updateList();
    }, []); /* If I add updateList within the [], it works, but it enters an infinite loop */

    useEffect(() => {
        console.log('List updated in the component:', list);
    }, [list]);

    const columns = [
        {
            title: 'Name',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: 'Price',
            dataIndex: 'price',
            key: 'price',
        },
        {
            title: 'Quantity',
            dataIndex: 'quantity',
            key: 'quantity',
        },
        {
            title: 'Amount Received',
            dataIndex: 'amountReceived',
            key: 'amountReceived',
        },
    ];

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

    return <Table dataSource={list} columns={columns} rowKey="ID" />;
};

export default SalesList;

UpdateList

import { useState, useEffect } from 'react';
import useFetchData from '../services/api/showData';

const UpdateList = () => {
    const { data, loading, error, fetchData } = useFetchData();
    const [list, setList] = useState([]);

    const updateList = async () => {
        try {
            const newList = await fetchData();
            setList([...newList]);
            console.log('New list obtained:', newList);
        } catch (error) {
            console.error('An error occurred while updating your data', error);
        }
    };

    useEffect(() => {
        updateList();
    }, [fetchData]);

    return { list, loading, error, updateList };
};

export default UpdateList;

ShowData

import { useState, useEffect, useCallback } from "react";
import axios from 'axios';

const useFetchData = () => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const fetchData = useCallback(async () => {
        setLoading(true);
        try {
            const response = await axios('http://localhost/REACT/my-app/src/backend/php/api/mostrarDatos.php');
            if (!response.data.ok) {
                return console.error('An error occurred, please restart. If the issue persists, contact the administrator.');
            }
            setData(response.data.respuesta);
            return response.data.respuesta;
        } catch (error) {
            setError(error instanceof Error ? error : new Error("An unknown error occurred"));
            console.error("Error fetching data:", error);
            return [];
        } finally {
            setLoading(false);
        }
    }, []);

    useEffect(() => {
        fetchData();
    }, [fetchData]);

    return { data, error, fetchData };
};

export default useFetchData;

I need that when updating the constant lista, the component that creates the table is updated, the hook is working but it is not re-rendering the data.

using tRPC with socket.io

I am creating a chat application and want to use socket.io with tRPC. Since tRPC has middleware support only for ws package, is there any workaround to use socket.io with tRPC?
The major reason I want to use socket.io is because I want the message exchange between users to be private and I don’t want to handle the user set on my own.

Adding some server code for context

app.use(
  "/trpc",
  createExpressMiddleware({
    router: appRouter,
    createContext,
  })
);

const server = app.listen(8080, () => console.log("listening at 8080"));

const wss = new ws.WebSocketServer({
  server
});
const io = new Server(server); // socket.io server

io.on("connection", (socket) => {
  console.log(`➕➕ socket Connection (${io.engine.clientsCount})`);
  io.once("close", () => {
    console.log(`➖➖ socket Connection (${io.engine.clientsCount})`);
  });
});

wss.on("connection", (ws) => {
  console.log(`➕➕ Connection (${wss.clients.size})`);
  ws.once("close", () => {
    console.log(`➖➖ Connection (${wss.clients.size})`);
  });
});

const handler = applyWSSHandler({
  wss,
  router: appRouter,
  createContext,
});

Is there any way to create a handler to work with socket.io? Or I would really appreciate if you could share what you think might be the best solution for this.