React Router Form and Action does not log the formsubmission

I attempted to use the react-router action and Form components, but it appears that the action function is not being invoked, and no errors are showing in the console. I have already implemented the Data router, exported the action function, and included it in the Router. Any insights on why the action function might not be triggering?

I’ve been following the React Router documentation, and my main concern is the absence of errors or warnings for debugging purposes.

Login component:

import React from 'react';
import { Form } from 'react-router-dom';

export async function action({ request }) {
  console.log(request);
  const data = await request.formData();

  const formSubmission = {
    email: data.get('email'),
    password: data.get('password'),
  };

  console.log(formSubmission);
}

const AdminLogin = () => {
  return (
    <div>
      <Form>
        <input
          type="text"
          placeholder="Enter email or User ID"
          name="email"
          autoComplete="username"
        />

        <input
          type="password"
          placeholder="Enter Password"
          name="password"
          autoComplete="current-password"
        />
        <button>Log In</button>
      </Form>
    </div>
  );
};

export default AdminLogin;

Router component:

import {
  Route,
  createBrowserRouter,
  createRoutesFromElements,
  RouterProvider,
  redirect
} from "react-router-dom";
import { Home, MainNav } from './Assets/User components/UserImports';
import './Assets/User components/StyledComponents/style.css';
import LogIn, { action as userAction } from "./Assets/User components/LogIn";
import Dashboard from "./Assets/Admin components/Dashboard";
import AdminLayout from "./Assets/Admin components/AdminLayout";
import EditDeals from "./Assets/Admin components/EditDeals";
import { loader } from "./Assets/User components/Deals";
import AdminLogin, { action } from "./Assets/Admin components/AdminLogin";

function App() {
  const takeRouter = createBrowserRouter(createRoutesFromElements(
    <>
      <Route path="*" element={<code>404 Not Found</code>} />
      <Route path="/" element={<MainNav />}>
        <Route path="adminlogin" action={action} element={<AdminLogin />} />
        <Route index element={<Home />} loader={loader} errorElement={<h1>Oh! there was an error!</h1>} />
        <Route path="login" action={userAction} element={<LogIn />} />
      </Route>
      <Route path="admin" element={<AdminLayout />} loader={async () => {
        const loggedIn = false;
        return loggedIn === false ? redirect('/adminlogin') : null;
      }}>
        <Route index element={<Dashboard />} />
        <Route path="editdeals" element={<EditDeals />} />
      </Route>
    </>
  ));

  return (
    <>
      <div className="app">
        <RouterProvider router={takeRouter} />
      </div>
    </>
  );
}

export default App;

React web worker error: Uncaught SyntaxError: Unexpected token ‘<' [duplicate]

I have this workerbuilder.js:

export default class WorkerBuilder extends Worker {
  constructor(worker) {
    super(worker);
    const code = worker.toString();
    const blob = new Blob([`(${code})()`]);
    return new Worker(URL.createObjectURL(blob));
  }
}

Then i have a worker.js:

export default () => {
  self.onmessage = (message) => {
    postMessage(message.data);
  };
};

I use it in another component (Test.tsx) like this:

import worker from './worker';
import WorkerBuilder from './workerBuilder';
const instance = new WorkerBuilder(worker);

But it failes already with the error:

() => {  self.onmessage = message => {    postMessage(message.data);  };}:1 Uncaught SyntaxError: Unexpected token '<' (at () => {  self.onmessage = message => {    postMessage(message.data);  };}:1:1)

Any ideas?

I am using it in a react app (create-react-app).
"react": "^18.2.0",

How to make ‘sort by price’ menu without rendering array twice?

I am trying to make a ‘sort by price’ menu for my e-commerce. I’ve tried using some logics but they always either break the code or render the array of objects twice, since I already made a ‘filter by category’ menu. I am still a bit new to React and it’s logics so I am still wrapping my head around this.

import React, { useEffect, useMemo, useState } from "react";
import "./VinylClocks.css";
import Navbar from "./Navbar.jsx";
import Footer from "./Footer.jsx";
import SortButton from "./SortButton.jsx";
import {data} from './data.js';
import Product from "./Product.jsx";

export default function VinylClocks() {

  const [dataList, setDataList] = useState([]);

  const [selectedCategory, setSelectedCategory] = useState();

  // Add default value on page load
  useEffect(() => {
    setDataList(data);
  }, []);

  // Function to get filtered list
  function getFilteredList() {
    // Avoid filter when selectedCategory is null
    if (!selectedCategory) {
      return dataList;
    }
    return dataList.filter((item) => item.cat === selectedCategory);
  }

  // Avoid duplicate function calls with useMemo
  var filteredList = useMemo(getFilteredList, [selectedCategory, dataList]);

  function handleCategoryChange(event) {
    setSelectedCategory(event.target.value);
  }
    return (
      <>
        <header className="header">
          <Navbar />
        </header>  
        <div className="vc-container">
          <div className="filter-sort">
            <div className="filter-container">
              <h5>Filter by Category:</h5>
              <select
              name="cat-list"
              id="cat-list"
              onChange={handleCategoryChange}
              >
                <option value="">All</option>
                <option value="movies">Movies</option>
                <option value="music">Music</option>
                <option value="sport">Sport</option>
                <option value="other">Other</option>
              </select>
            </div>

            <SortButton /> 
            
          </div> 
          <div className="products-container">
          {filteredList.map((items, id) => (
      <Product {...items} key={id} />
    ))}  
          </div>
        </div>  
          <Footer />
      </>
    );
  }

Sort button component

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faArrowDownWideShort } from '@fortawesome/free-solid-svg-icons';
import { useState } from 'react';
import "./SortButton.css";


export default function SortButton() {
    
const [select, setSelect] = useState("");
    return (
        <>
          <div className="sort-dropdown">
                <FontAwesomeIcon icon={faArrowDownWideShort} style={{color: "#021027",}} />
                <select value={select} 
                onChange={e=>setSelect(e.target.value)}>
                    <option>Sort by: Latest</option>
                    <option>Sort by: Price:High to Low</option>
                    <option>Sort by: Price:Low to High</option>
                </select>
         </div>
        </>
    )
}

I get this error. Error: could not find react-redux context value; please ensure the component is wrapped in a

when I use useDispatch in my NextJs Porject, I get this error and everything stops working
Here is the error:
Error: could not find react-redux context value; please ensure the component is wrapped in a

import { Provider, useDispatch } from 'react-redux';
import { store } from '../redux/store';
import axios from "axios";


axios.defaults.withCredentials = true;


const AppComponent = ({ Component, pageProps }) => {
  const dispatch = useDispatch()

  useEffect (() => {
    dispatch(getLoginInStatus())

  },[dispatch])

  return (
    <Provider store={store}>
      <div>
        <ToastContainer />
        <Component {...pageProps} />
      </div>
    </Provider>
    
  )
} 

export default AppComponent

my Provider is properly used, what could be wrong ?

TypeError: isRequiredIf is not a function

everyone
I’m using react-joyride(“2.5.3”) trough my project, and after yesterday react-floater new version release(0.7.7) my build is broken.

Please let me know how to fix this.

Error text :
Collecting page data ..TypeError: isRequiredIf is not a function at Object.<anonymous> (/node_modules/react-floater/lib/index.js:211:7832) at Module._compile (node:internal/modules/cjs/loader:1254:14) at Module._extensions..js (node:internal/modules/cjs/loader:1308:10) at Module.load (node:internal/modules/cjs/loader:1117:32) at Module._load (node:internal/modules/cjs/loader:958:12) at Module.require (node:internal/modules/cjs/loader:1141:19) at mod.require (/node_modules/next/dist/server/require-hook.js:64:28) at require (node:internal/modules/cjs/helpers:110:18) at Object.<anonymous> (/onboard-t3/node_modules/react-joyride/lib/index.js:15:15) at Module._compile (node:internal/modules/cjs/loader:1254:14)

I found in my package-lock file that react-floater is a dependencie to react-joyride, and version is not fixed.
Shall I remove joyride from my product?

Code splitting vue-i18n translation files in vue 3 (composition api)

I’ve been successfully using vue-i18n in my Vue 3 app but as the app grows the translation file is getting really big. And there are a small number of pages that aren’t often requested that add a lot of text. I’d like to split those strings into a separate file and only load that file when the user goes to that page – you know, the way Vite is already doing wonderfully with my javascript.

Here’s the relevant part of my setup in main.ts:

import { createI18n } from "vue-i18n";
import { messages } from "@/i18n/messages";

export const i18n = createI18n({
    legacy: false,
    locale: "en",
    messages,
});

app.use(i18n)

And here’s how I use it in my component:

import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });

Is there a way to create a separate translation file and pass it directly into that useI18n call so that it is only referenced on the pages that call that component?

@dnd kit list sorting not working properly when parent div has transform:scale() css

@dnd-kit list sorting not working properly when parent div has transform:scale() css.

In one of my project there is one feature for zoom In/Out. And That I am managing with transform:scale(). But now in the child component I am using @dnd-kit sortable library to sort my blocks. but because of that transform:scale() css sorting is not working properly like cursor and block are not moving aligned.

here is my demo link: https://codesandbox.io/p/sandbox/dndkit-sorting-4gxnz7.

I’m receiving this error when trying to run my application using the npm start command

> npm start  
npm ERR! Missing script: "start"
npm ERR!
npm ERR! Did you mean one of these?
npm ERR!     npm star # Mark your favorite packages
npm ERR!     npm stars # View packages marked as favorites
npm ERR!
npm ERR! To see a list of scripts, run:
npm ERR!   npm run

npm ERR! A complete log of this run can be found in: C:UsersDELLAppDataLocalnpm-cache_logs2023-12-06T16_20_11_109Z-debug-0.log

I want to run Parcel.

Unable to access data from the request when using multipart/form-data in Fetch

I am using the Fetch API in JavaScript. Up until now, I was using implicit set on the Content-Type header which is built in the browser. I.e: If the user sends JSON, the browser will set the Content-Type to application/json. If I send FormData, the browser will set the Content-Type to multipart/form-data.

This works well, but I am using an older version of a bundler that builds my web-app to an Android app which does not set the content-type header automatically.

For this, I need to explicitly define which content type I am using. However, when I do specify the content type explicitly, my request does not get processed correctly by the server – the server does not get the provided fields sent into the FormData object.

Here is how I send the request:

var myHeaders = new Headers()
myHeaders.set("content-type", "multipart/form-data")

var formdata = new FormData();
formdata.append("email", "[email protected]");
formdata.append("password", "MySuperSecretPasswordOMG!");

var requestOptions = {
  method: 'POST',
  body: formdata,
  headers: myHeaders,
  redirect: 'follow'
};

console.log(formData) // Here I see FormData {email: "[email protected]", password: "MySuperSecretPasswordOMG!" }

fetch("http://192.168.1.123:5000/users/auth/login", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

My server responds with error code 400 which I coded to return when any required fields are missing from the request:

# Login validator created in Flask
data = request.form # email and password are NOT present in request.
required_keys = ["email", "password"]

if not self.validate(required_keys, data):
    return self._abort(400, "Incorrectly formatted request. Please make sure that all the required fields are entered.")

# Additional functions which are used above.
@staticmethod
def _abort(code, message):
    return jsonify({"msg": message, "code": code}), code

def validate(self, keys, data):
    for key in keys:
        if key not in data:
            return False
    return True

Am I doing something wrong? Is this a browser-related issue? Is this a backend/frontend related feature?

Electron + React, how do you “link” variables between jsx and main.js/renderer.js?

I’m using Electron with React and started implementing some basic components like input text.
Before that I wasn’t using react, and made things work with the renderer.js like this :

const item = document.getElementById('MyItem');
function OnMyOwnEvent({target : {value}})
{
  window.API.ownEvent(value); // API and ownEvent declared in Preload.js
}

And in Main.js, I could retrieve the value like this :
ipcMain.handle(‘ownEvent’, (_event, value) => …

But with React, getElementById does not work as it seems to get elements from the index.html file, (but now all the elements have moved to App.jsx).

So my question is, how do you get values changed from App.jsx to Main.js?

click() works but nothing happens on the screeen

I am using click() on an element, it seems like thee click works, becuase the console.log() fires after the click. But nothing happens in the web-browser.

I am pressing an element that opens a calander and then i scrape the active dates of numbers. Add the numbers to an object push the object to an array. After I have done this i need to:

-> Press the calander again
-> Find the btn that change the month and repeat the above.

The repo is here: repo.

I expect the month to be changed in the Carlander view.

I have tried to add:
await page.waitForNavigation({ waitUntil: "load" }); but nothing else.

I really dont know how to de-bug this or find out why it isnt changing the month.

Detecting a pause of 2 Seconds or more in Speech

is there any reliable and consistent method to detect a pause of more than 2 seconds in AssemblyAi realtime transcript.

https://www.assemblyai.com/docs/guides/real-time-streaming-transcription

currently my implementation is this.

if(currentFinalTranscript.audio_start - previousFinalTranscript.audio_end  >= 2000){
    console.log("pause greater than 2 seconds detected");
}

this works well when the pause duration is 5000 instead of 2000.
but the more near i go to 2000 it starts getting unreliable.

i am assuming that the audio_start and audio_end in the realtimeTranscript response excludes the milliseconds where the person was silent.
as this seems to be the case when the pause is longer.

currentFinalTranscript is the finalTranscript recieved in the new socket.onMessage

previousFinalTranscript is the finalTranscript recieved in the preceeding socket.onMessage callback

other logical approaches or flaws in the current logic are welcomed.

Vue conditionally update options of a select input based on the value of previous select input using FormKit

I am working on a multistep form in Vue and Formkit. It has four steps:

  1. Group Info
  2. Practices
  3. Locations
  4. Providers

Practices, Locations, and Providers are ‘repeaters’ – where you can add multiple groups of data, creating an array of objects.

{
  "formSteps": {
    "groupStep": {
      "fullAddress": {},
      "pointOfContact": {},
      "contractApproval": {}
    },
    "practiceStep": {
      "practices": [
        {
          "name": "test 1",
          "id": "0"
        },
        {
          "name": "test 2",
          "id": "1"
        },
        {
          "name": "test 3",
          "id": "2"
        }
      ]
    },
    "locationStep": {
      "locations": [
        {
          "practiceId": "0",
          "name": "ent office",
          "id": "0",
          "emr": {},
          "fullAddress": {},
          "officeManager": {}
        },
        {
          "practiceId": "1",
          "name": "dentist office",
          "id": "1",
          "emr": {},
          "fullAddress": {},
          "officeManager": {}
        }
      ]
    },
    "providerStep": {
      "providers": [
        {
          "id": "0",
          "practice": "0",
          "primaryLocation": ""
        }
      ]
    }
  }
}

In the Providers step, there is a “Practice” select where the options are created by iterating over formSteps.practiceStep.practices.

<FormKit
   type="select"
   label="Practice"
   name="practice"
   :id="`provPractice_${index}`"
>
   <option value="" selected disabled>Select a practice...</option>
   <option v-for="(practice, index) in formData.formSteps.practiceStep.practices" :key="index" :value="practice.id">{{ practice.name }}</option>
</FormKit>
<FormKit
   type="select"
   label="Primary Location"
   name="primaryLocation"
   :id="`provPrimaryLocation_${index}`"
   v-model="`provPractice_${index}`.value"
>
   <option value="" selected disabled>Select a location...</option>
   <!-- Dynamically rendered options that match practiceId here -->
</FormKit>

Underneath it is a “Primary Location” select where the options needs to be dynamically rendered by comparing the value of the option selected in “Practice” to practiceID in formSteps.locationStep.locations, and if they equal, populate the matching options.

What would be the best way to tackle this?

FormKit documentation offers a flat, simple example here

<script>
const flavors = computed(() => {
  if (formData.value.food === 'Ice Cream') {
    return ['Chocolate', 'Vanilla']
  }
  return ['Pepperoni', 'Cheese']
})
</script>

<template>
  <FormKit type="form" v-model="formData">
    <FormKit
      type="select"
      label="Food"
      name="food"
      :options="['Pizza', 'Ice Cream']"
    />
    <FormKit
      type="select"
      label="Flavor"
      name="flavor"
      :options="flavors"
    />
  </FormKit>
</template>

I’m just unsure on how to do something similar with the more complex data in my case.

How to change the white tick color when using Material UI Checkbox (React, JS)

I’m trying to change the default white tick (not the checkbox background!) to some other color of my choice. I’ve found some solutions for when using an older version of MUI and React. I’m looking for a solution for MUI v5.14 and React v18

MUI checkbox for reference: https://mui.com/material-ui/react-checkbox/

Found this post, but it seems not relevant for the current versions:
https://stackoverflow.com/questions/57970631/change-the-tick-color-in-muicheckbox-material-ui#:~:text=There%20is%20actually%20no%20color,the%20tick%20should%20be%20colored.

How to trigger HTML5 form validation on input

I have a form like this. The value comes from the database, and the user should fix the problem that keeps it from validating.

<style> input:invalid {border: 3px solid red} </style>
<form>
    <input type="text" id="name" maxlength="10" value="A very very long name !">
</form>

I would expect that the input field is :invalid, but it isn’t. input.checkValidity() and form.reportValidity() both return true.

Once I edit the field (delete a character), the field becomes invalid, and the javascript functions return false as expected.

How can I trigger the HTML validation through Javascript, instead of through user interaction?