Share Form Fields In Different Forms

I have a login and register form(from react hooks) in my application. I want to reuse common fields for both forms.

Therefore, I have created components like emailField, passwordField etc. Since register form contains fields in login form I have derived RegisterFormFields from LoginFormFields. and in emailField.tsx I have defined

interface EmailFieldParameterTypes {
    register: UseFormRegister<LoginFormFields>;
    errors: FieldErrors<LoginFormFields>;
}

where I hope to be able call emailField both with UseFormRegister<RegisterFormFields> and UseFormRegister<LoginFormFields> but I was not. the typescript compiler gave

Type 'UseFormRegister<RegisterFormFields>' is not assignable to type 'UseFormRegister<LoginFormFields>'.
  Type 'LoginFormFields' is missing the following properties from type 'RegisterFormFields': username, firstname, surnamets(2322)
emailField.tsx(5, 5): The expected type comes from property 'register' which is declared here on type 'IntrinsicAttributes & EmailFieldParameterTypes'

error even though RegisterFormFields extends LoginFormFields. I have also tried somethings with generics but it didn’t workout. appriciated for any help.

referred files:

emailField.tsx

import { FieldErrors, UseFormRegister } from 'react-hook-form';
import { LoginFormFields } from '../../login/loginForm';

interface EmailFieldParameterTypes {
    register: UseFormRegister<LoginFormFields>;
    errors: FieldErrors<LoginFormFields>;
}

const EmailField = ({ register, errors }: EmailFieldParameterTypes) => {
    return (
        <label className="flex flex-col gap-1">
            <div>Email</div>
            <input
                className="p-2 border border-gray-500 shadow bg-gray-200"
                id="email-input"
                type="email"
                placeholder={"enter your email"}
                {...register("email", { required: "email is required!" })}
            />
            {errors.email && <p className="text-red-400">{errors.email.message}</p>}
        </label>
    );
};

export default EmailField;

registerForm.tsx

import { useForm } from "react-hook-form";
import EmailField from "../components/form-fields/emailField";
import PasswordField from "../components/form-fields/passwordField";
import UsernameField from "../components/form-fields/usernameField";
import { LoginFormFields } from "../login/loginForm";

export interface RegisterFormFields extends LoginFormFields {
    username: string
    firstname: string
    surname: string
}

const RegisterForm = () => {

    const {
        register,
        handleSubmit,
        formState: { errors },
    } = useForm<RegisterFormFields>()

    const onSubmit = handleSubmit((data) => console.log(data))

    return (
        <form onSubmit={onSubmit}
            className="flex w-100 px-12 py-8 flex-col gap-3 max-w-xl shadow 2xl border border-gray-300 rounded-2xl">
            <EmailField register={register} errors={errors} />
            <PasswordField register={register} errors={errors} />
            <UsernameField register={register} errors={errors} />
            <button className="bg-blue-400 rounded shadow text-white text-lg p-2">
                Giriş Yap
            </button>
        </form>
    )
};

export default RegisterForm;

LoginForm.tsx

import { useForm } from "react-hook-form";
import EmailField from "../components/form-fields/emailField";
import PasswordField from "../components/form-fields/passwordField";

export interface LoginFormFields {
    email: string
    password: string
}

const LoginForm = () => {

    const {
        register,
        handleSubmit,
        formState: { errors },
    } = useForm<LoginFormFields>()

    const onSubmit = handleSubmit((data) => console.log(data))

    return (
        <form onSubmit={onSubmit}
            className="flex w-100 px-12 py-8 flex-col gap-3 max-w-xl shadow 2xl border border-gray-300 rounded-2xl">
            <EmailField register={register} errors={errors} />
            <PasswordField register={register} errors={errors} />
            <button className="bg-blue-400 rounded shadow text-white text-lg p-2">
                Giriş Yap
            </button>
        </form>
    )
};

export default LoginForm;

Is there no way to create components dynamically using only Astro?

I’m working on an Astro project where I’m building a classic Pokédex. I have a PokemonCard.astro component that renders a Pokémon’s details, and I’m trying to load more Pokémon dynamically when a “Load More” button is clicked. However, I’m currently creating the HTML elements manually in JavaScript, which feels redundant since I already have a PokemonCard component (I tried to reuse my component in the script but it doesnt work).

Is there a way to dynamically create and render Astro components (like PokemonCard) in the browser without manually creating the HTML elements? If not, what’s the best approach to achieve this?

Here’s the code:

---
import Layout from '../layouts/Layout.astro';
import PokemonCard from '../components/PokemonCard.astro';
import { getPokemons } from '../lib/controllers/pokemonController';
import type { PokemonSmall } from '../lib/models/pokemonModels';



const pokemons: PokemonSmall[] | undefined = await getPokemons(0, 12);
---

<Layout title="Pokedex">
<main class="m-auto">
    <section id="pokemon-grid">
        <div class="grid grid-cols-2 gap-7 p-2 mt-32
        md:grid-cols-4">
            {
                pokemons?.map((pokemon : PokemonSmall) => (
                        <PokemonCard {pokemon}/>
            ))
            }
        </div>
    </section>
    <section class="flex justify-center items-center">
        <button id="load-more-pkmn"
        class="p-4 bg-slate-400/20 border-gray-500 border rounded-2xl my-4 
        transition-transform transform hover:scale-105">Cargar más pokémons</button>
    </section>

</main>
</Layout>

<script>
import { getPokemons } from "../lib/controllers/pokemonController";
import { TypeColors, type PokemonSmall, type PokemonType } from "../lib/models/pokemonModels";
import { capitalizeFirstLetter, mapId } from "../lib/utils/utils";


    let offset = 12; 
    const limit = 12;

    const loadMorePkmn = document.getElementById('load-more-pkmn');
    if(loadMorePkmn) {

        loadMorePkmn.addEventListener('click', async () => {

            const pokemons : PokemonSmall [] | undefined = await getPokemons(offset, limit);
            offset += 12;

            const pokemonGrid = document.getElementById('pokemon-grid');

            const divPokemons = document.createElement('div');
            divPokemons.className = 'grid grid-cols-2 gap-7 p-2 md:grid-cols-4';
            
            pokemons?.map((pokemon : PokemonSmall) => {

                console.log(pokemon)

                const a = document.createElement('a');
                a.className = 'w-60 h-60 p-1 flex flex-col items-center bg-slate-400/10 border-gray-500 border rounded-2xl hover:bg-gray-200 cursor-pointer';
                const image = document.createElement('img');
                image.className = 'w-28';
                const h3 = document.createElement('h3');
                h3.className = 'text-2xl font-bold tracking-wide mt-1';
                const p = document.createElement('p');
                p.className = 'text-xs tracking-wide p-1';
                const divTypes = document.createElement('div');
                divTypes.className = 'flex flex-row space-x-1 mt-2 p-1 gap-2';


                a.href = `pokemon/${pokemon.id}`;   
                image.src = pokemon.image; image.alt = `Una foto de ${pokemon.name}`;
                a.appendChild(image);
                h3.innerText = capitalizeFirstLetter(pokemon.name);
                a.appendChild(h3);
                p.innerText = `No. ${mapId(pokemon.id)}`;
                a.appendChild(p);

                pokemon.types.map((types : PokemonType) => {

                    const pType = document.createElement('p');
                    pType.className = ` ${TypeColors[types.type.name]} opacity-80 rounded text-white text-center font-medium tracking-wide py-1 px-2`;
                    pType.innerText = types.type.name;
                    divTypes.appendChild(pType);
                   
                });
                a.appendChild(divTypes);
                
                
                divPokemons.appendChild(a);
            });

            pokemonGrid?.appendChild(divPokemons);
        });
    }
</script>

I thought about using a frontend framework like React or Vue, but I’d like to stick to Astro if possible.

Using webpack serve and files not auto reloading when there are changes

I am going crazy
Help me Whenever I run webpack serve, and make changes to the HTML files it would not auto-reload. This is my webpack config file:

const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
  entry: "./src/bundle.js", // Entry file
  mode: 'development',
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js",
  },
  devtool: "inline-source-map", // Enable source maps for development
  devServer: {
    // filename: "bundle.js",
    static:{
      directory: path.resolve(__dirname, "dist"),
    
    },
    //path.resolve(__dirname, "dist"), // Serve files from `dist`
    // historyApiFallback: true, // Redirect 404s to `index.html`
    port: 8000, // Use port 8000
    hot: true // Enable Hot Module Replacement
  },
  module: {
    rules: [
      {
        test: /.css$/i,
        include: path.resolve(__dirname, 'src'),
        use: ['style-loader', 'css-loader', 'postcss-loader'],
      },
      {
        test: /.html$/i,
        loader: "html-loader",
      },
      {
        test: /.js$/,
        exclude: /node_module/,
        use:{
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        },
        
      },
      {
          test: /.(png|svg|jpg|jpeg|gif)$/i,
          type: 'asset/resource',
          use: ['style-loader', 'css-loader'],
      },
    ],
  },
  plugins: [
    new CleanWebpackPlugin(), // Clean the output directory before each build
    new HtmlWebpackPlugin({
      filename: "index.html", // Output HTML file
      template: "./src/todo.html", // Template HTML file
    }),
  ],
  
};

This is the HTML file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Webpack Setup Example</title>
  </head>
  <body>
    <!-- box -->
    <h1>hi</h1>
    <div class="bg-blue-100 size-40">sss</div>
    <script src="bundle.js"></script>
  </body>
</html>

this is bundle.js:

import './style.css';

This is the files that I would get if I run npx webpack:

the a687oae js file has import ‘style.css’

This is the tree

Issues with calling a javascript event/function in a user control

i have a user control that is displayed up to 10 times on a page based off user input. pretty basic function. text area with a word limit counter. everytime a user types the counter is updated. issue is when you update any of the controls other than the first, it just updates the values in the first control. I understand what the issue is but i am having trouble figuring out how to fix the issue. Included below is a code snippet.

<span> (<span id="txMerchant"> 200 </span> characters left)</span>
<asp:TextBox runat="server" id="txtmerchant" TextMode="MultiLine" Columns="3" onKeyDown="maxTextLimit(this,200,'txMerchant;)" </asp:Textbox> 

maxTextLimit is your basic function that checks length vs max length and updates

How to mock DataTransfer constructor in Jest?

I made a custom hook, useFileListState, that basically encapsulates the logic to add and remove files from a FileList.

To remove (or add) it, it uses the DataTransfer constructor, as well as the property files and the method items.add():

function deleteFile(fileToDelete: File) {
  setData((prevData) => {
    if (!prevData) return null;

    const fileToDeleteId = getFileToken(fileToDelete);
    const dt = new DataTransfer();

    for (let i = 0; i < prevData.length; i++) {
      const file = prevData[i];
      const id = getFileToken(file);
      if (id !== fileToDeleteId) dt.items.add(file);
    }
   return dt.files;
  });
}

The problem is, Jest doesn’t recognize the DataTransfer constructor, so I need to mock it somehow, which I tried to do this way:

class mockDataTransfer {
  files: File[] = [];
  items = {
    add: (file: File) => {
      this.files.push(file);
    },
  };
}

jest.spyOn(global, "DataTransfer").mockImplementation(() => mockDataTransfer as unknown as DataTransfer);

But this fails because Property 'DataTransfer' does not exist in the provided object.

Can someone help me mocking the DataTransfer constructor?

Autoselect Option 1 on multiple SELECT Form Fields? [duplicate]

I have a short script to automatically default a SELECT form field to its first option. This works great although when adding a second SELECT within the same form it ignores it. Obviously I need this to run in some sort of loop for each occurrence of a dropdown. Thanks.

<script>
    /* Set Select Input defaults to first option Value */
    const selectElement = document.querySelector('select');
    selectElement.selectedIndex = "1";
</script>

React native app stops firebase listener after loggin BUNDLE ./index.js

I am working on a React Native app that uses Firebase Realtime Database and FCM notifications. I set up a listener to listen for changes in the Firebase database and trigger local notifications using react-native-push-notification.

However, the problem is that after Metro logs:

BUNDLE  ./index.js 
  • In App notifications stopped working.
  • The only way to restore them is to restart the app manually.

What I Have Tried:

  • Reattaching Listeners in useEffect

Tried setting up Firebase listeners inside useEffect when the component mounts.

  • Using AppState to Restart Listeners

tried detecting app state changes (active, background) and restarting the listener.

  • Ensuring Listeners Are Not Removed

Checked that .off() is only called before reattaching listeners to avoid duplication.

  • Disabling Metro Fast Refresh

Tried adding liveReload: false in Metro settings to prevent unnecessary reloads.

My Current Notification Listener Code:


import { AppState } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import database from '@react-native-firebase/database';
import PushNotification from 'react-native-push-notification';

const listenForNotifications = async () => {
  console.log('Listening for notifications...');
  try {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;

    if (!enabled) {
      console.log('User denied notification permissions');
      return;
    }

    const token = await messaging().getToken();
    if (!token) {
      console.log('FCM token not available');
      return;
    }

    const notificationRef = database().ref('notifications').child(token);

    // Remove existing listeners to avoid duplication
    notificationRef.off();

    notificationRef.on(
      'value',
      snapshot => {
        if (snapshot.exists()) {
          const notificationData = snapshot.val();

          PushNotification.localNotification({
            channelId: 'default',
            title: notificationData?.notification?.title || 'New Notification',
            message: notificationData?.notification?.body || 'You have a new message',
            playSound: true,
            soundName: 'default',
            importance: 'high',
          });
        }
      },
      error => {
        console.error('Error listening to notifications:', error);
      }
    );

    return () => {
      notificationRef.off();
    };
  } catch (error) {
    console.error('Error setting up notification listener:', error);
  }
};

// Restart listener when the app state changes
import { useEffect } from 'react';

const App = () => {
  useEffect(() => {
    const handleAppStateChange = (nextAppState) => {
      if (nextAppState === 'active') {
        console.log('App became active, restarting listener...');
        listenForNotifications();
      }
    };

    const subscription = AppState.addEventListener('change', handleAppStateChange);

    // Run listener on first mount
    listenForNotifications();

    return () => {
      subscription.remove();
    };
  }, []);

  return (
    // Your App UI
  );
};

export default App;

What I Need Help With:

  • Why do my Firebase listeners stop working after BUNDLE ./index.js is logged?
  • How can I prevent Firebase listeners from being lost when Metro refreshes the app?
  • Is there a way to automatically restore all listeners when this happens?

this ** BUNDLE ./index.js ** log is my main problem…, don’t know why it appears randomly in some of the notifications, it’s completely random, sometimes Notifications keep working, and some time this logs appear when a new notification arrive first time and then it stopped there

Date parsing uses incorrect TZ

I am located in NY, which is GMT-5 now. Calling the following in both Chrome and nodejs returns same results:

> Intl.DateTimeFormat().resolvedOptions().timeZone
'America/New_York'
> new Date().getTimezoneOffset()
300

However if I do

> date = new Date("2024-08-01T04:30:57Z");
2024-08-01T04:30:57.000Z

it parses it (or rather formats) as if I was in GTM-4:

> date.toLocaleString()
'01.08.2024, 00:30:57'
> date.getTimezoneOffset()
240
> > date.toLocaleString("en-US", {timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone})
'8/1/2024, 12:30:57 AM'

Why so?

Only works if I explicitly tell it to use correct TZ:

> date.toLocaleString("en-US", {timeZone: "-05:00"})
'7/31/2024, 11:30:57 PM'

or the same, but TZ string is created programmatically

> offsetInMinutes = new Date().getTimezoneOffset();
300
> offsetHours = Math.floor(Math.abs(offsetInMinutes) / 60).toFixed(0).padStart(2, "0");
'05'
> offsetMinutes = (Math.abs(offsetInMinutes) % 60).toFixed(0).padStart(2, "0");
'00'
> offset = `${offsetInMinutes > 0 ? "-" : "+"}${offsetHours}:${offsetMinutes}`;
'-05:00'
> date.toLocaleString("en-US", {timeZone: offset})
'7/31/2024, 11:30:57 PM'

Tabulator dataTree updateData() _children elements

I am taking advantage of Tabulator’s dataTree module to represent data organized into categories. I have the ability to manipulate the state of the _children nested data and would like to convey this state to the table. I’ve tried to update a single sub row, via updateData() by passing:

{ id: "unique_id", column1: "foo", column2: "bar", _children: [ { id: "another_id", column1: "foo", ...} ] }

However, if I had say 10 entries in _children, the array will be reduced to my single update. Is there a means to update a single child without having to process the whole parent categorical element?

Here is an example fiddle of the behavior I’m seeing when trying to update a single row in _children: https://jsfiddle.net/4gswxp05/1/

Additionally, it looks like if I don’t include all fields of the child, those will be lost as well.

I think my fallback would be to supply the entire parent row to include all children plus the update, but for my circumstance, I could end up with several updates in a short window and would rather not send such a large update if I can help it.

Thank you for your assistance!

Running Typescript Unit Tests with Jest and Bazel?

If trying to see if I also want to run a repositories Typescript tests with Bazel and I’m going through this tutorial on how to do it. And it says the jest_test rule can be configured like this:

jest_test(
    name = "test",
    config = "jest.config.js",
    data = [
        "src/index.ts", # the test file below depends on this file
        "tests/index.test.ts",
    ],
)

But specifying the relationship between each source file and the corresponding test file is considerable extra work.

Does anyone know if there is a way around this?

MongoServerError: ‘timestamp_property’ must be present and contain a valid BSON UTC datetime value

I’m encountering the following error when trying to post sensor data to my API:
MongoServerError: ‘timestamp_property’ must be present and contain a valid BSON UTC datetime value.

Here’s the code for my test:

test("POST /api/sensors/:id/data - Should add new sensor data", async () => {
    const fakeId = new mongoose.Types.ObjectId();

    const sensorData = {
      name: "New Sensor",
      property_2: "Room B",
      timestamp_property: new Date(), // Valid Date object
      metadata_property: { location: "Lab 2", type: "Humidity" },
    };

    console.log(`New response is ${sensorData.timestamp_property}`);

    const response = await request(app)
      .post(`/api/sensors/${fakeId}/data`)
      .set("Content-Type", "application/json")
      .send(sensorData);

    expect(response.status).toBe(201);
    expect(response.body.task.name).toBe("New Sensor");
});

This is my Mongoose model:

const mongoose = require("mongoose");

const TaskSchema = new mongoose.Schema(
  {
    name: String,
    property_2: String,
    timestamp_property: Date, // Should be a Date
    metadata_property: Object,
  },
  {
    timeseries: {
      timeField: "timestamp_property",
      metaField: "metadata_property",
      granularity: "hours",
    },
  }
);

module.exports = mongoose.model("Task", TaskSchema);

I’ve ensured that timestamp_property is being set to a Date object, but I’m still getting the MongoServerError. Could someone explain what might be causing this issue?

Thanks in advance!

I’ve ensured that timestamp_property is being set to a Date object, but I’m still getting the MongoServerError.

I tried to change the CSS of an Ionic element

I’m trying to learn Ionic with Vue.js.
I want to do something simple: just change the background color, but it doesn’t work.
I don’t found good documentation explaining how can i do that

<template>
  <ion-page>
    <ion-header>
      <ion-toolbar class="header">
        <img class="icon" src="/icon.svg"/>
        <ion-title class="title">Name</ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content :fullscreen="true">
      <ion-header collapse="condense">
        <ion-toolbar>
          <ion-title size="large">Tab 1</ion-title>
        </ion-toolbar>
      </ion-header>

      <ExploreContainer name="Tab 1 page" />
    </ion-content>
  </ion-page>
</template>

<script setup lang="ts">
</script>

<style>
  .icon {
    width: 4rem;
    height: auto;
    margin-right: 8px;
  }

  ion-header {
    background-color: red;
  }
</style>

thanks

How to pass the ViewBag from the view to external Javascript code

I have this method that passes a List if the error occurs:

if (userList.Find(U => U.Id == userViewModel.Id) != null)
{
    _response.ApiErrorList = new List<string> { "User already exist" };
    _response.StatusCode = HttpStatusCode.BadRequest;

    return BadRequest(_response);
}

I serialize the list and pass it to the TempData[“ApiErrorList”]

 if (ApiResponse.StatusCode == HttpStatusCode.BadRequest)
 {
 if (ApiResponse.ApiErrorList.Count > 0)
 {
      TempData["ApiErrorList"] = JsonConvert.SerializeObject(ApiResponse.ApiErrorList);
    
      return RedirectToAction(redirectViewName, userViewModel);
 }

I pass TempData to the ViewBag to pass it to the view:

if (TempData["ApiErrorList"] != null)
{
    ViewBag.ApiErrorList = TempData["ApiErrorList"];
}

In the HTML page I inserted this code:

<input type="hidden" id="apiErrorList" data-value1="@ViewBag.ApiErrorList" />

In the external javascript page I inserted this code:

var apiErrors = $("#apiErrorList").data("value1");

but apiErrors is undefined.

<input type="hidden" id="apiErrorList" data-value1="["User already exist"]">

This is the result in the html page when the hidden field is valorised with the viewbag, why is the javascript part unable to take the value in the data-value1 field?

The problem is that apiErrors is always undefined

Using ajax with php://output

I’m using Phpspreadsheet to generate excel file with data. I want my file to be downloaded immediately after creation by user. It is easy to obtain using:

$writer = new Xlsx($spreadsheet);
$writer->save('php://output');

this allows to open download window directly in the browser instead saving copy of file on server.

My php file with this method is called after pressing button on a page and contains also some SQL queries to get data for Excel file. It is called using GET with few parameters. Due to that it could be very useful to use ajax and as result of query to have download and in case of error display some message.
Unfortunetly I don’t know how to obtain this effect in success clause of ajax query.
Now I’m using:

windows.location="/Excel_export_page.php?parameters=export_parameters"

I’d like to use

$.ajax({
   url: "/Excel_export_page.php",
   type: "GET",
   ....
   data: {
      parameters : export_parameters
   },
   success: function(data) {
      //display download window in browser
   },
   error: function() {
      alert("Error")
   }

Is it possible ?

Ninja Form wordpress plugin reload page after submit

I use ninja forms plugin in wordpress. I submit the form successfully, get a message about it. Everything fine. But if after it I fill the form again and submit, the page is reloaded, but before that data is submitted and fields with values are added to URL of the site. My question is how can I send the form many times without page reloading?

I have tried reset the form after submit in this:

jQuery(document).on('nfFormSubmitResponse', function(event, response) {

Or catch onsubmit:

jQuery(foorm).on('nfFormSubmit', function(event, formData) {

or

jQuery('.nf-form-layout form').on('submit', function(event) {

Thank you!