Cuando lleno el formulario, solo puedo obtener las coordenadas de geolocalización de mi propia cuenta si lo comparto con otras personas no lo hace [closed]

Buenos dias estoy realizando un aplicación que cuando los personas que llenan el formulario me tome su geolocalización y la capture en la hoja de respuestas (Esto para controlar que los empleados de una empresa cuando reporten su ingreso a planta lo realicen desde el sitio de trabajo donde existe un Código QR y no desde otro sitio diferente al area de trabajo simplemente con una captura de pantalla del Codigo QR) para esto realicé el siguiente Código, Funciona perfectamente con mi Cuenta es decir cuando lo hago desde mi Celular al compartir el Formulario con los demas aunque captura toda la inf en la hoja de Google las coordenadas no lo realiza, será que ellos deben dar un permiso para su geolocalización?
enter image description here

enter image description here

Funciona muy bien cuando lo hago yo mismo, en mi propia cuenta, captura las coordenadas en un campo de la hoja de respuestas, que luego pego en google Maps y alli encuentro mi ubicación exact, pero cuando lo comparto el formulario con otro usuario este ya no lo hace
aparece el siguiente mensaje:
enter image description here

React Hook Form multi-step form only submits last step’s values – how to preserve and submit all step values?

I’m building a reusable form component in React that supports both:

  1. Simple (single-step) forms, and
  2. Multi-step forms (each step has its own schema and inputs).

I’m using:

  • react-hook-form
  • Zod for schema validation
  • Custom wrapper components like FormWrapper, RHFInput

Problem:

  • Each step has its own Zod schema and inputs(there can be many inputs like select, multi select, switch, text area, etc. I am taking two inputs in each step) (e.g., name in step 1, email in step 2).
  • Validation works fine for each step individually.
  • On submitting, I only get the values of the last step.
  • When I fill all inputs, go to the next step, then go back — it shows values from the next step instead of restoring the previous step’s inputs correctly.
  • Going back to a previous step loses the earlier step’s field values.
  • On final submission, I only get the values from the last step (e.g., just email) — values from earlier steps (e.g., name) are missing.
  • I want to preserve values from all steps, and on submit, combine and submit all form values.

RHFInput.tsx

import {
  forwardRef,
  memo,
  type Ref,
  type RefCallback,
  type RefObject,
} from "react";
import { useFormContext, type FieldValues, type Path } from "react-hook-form";
import {
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";

type RHFInputProps<T extends FieldValues> = {
  name: Path<T>;
  label?: string;
  placeholder?: string;
  type?: string;
  disabled?: boolean;
};

function mergeRefs<T>(...refs: (Ref<T> | undefined)[]): RefCallback<T> {
  return (value: T) => {
    refs.forEach((ref) => {
      if (typeof ref === "function") {
        ref(value);
      } else if (ref && typeof ref === "object") {
        (ref as RefObject<T>).current = value;
      }
    });
  };
}

// 1. Define generic component WITHOUT forwardRef:
function RHFInputInner<T extends FieldValues>(
  { name, label, placeholder, type = "text", disabled }: RHFInputProps<T>,
  ref: Ref<HTMLInputElement>
) {
  const { control } = useFormContext<T>();

  return (
    <FormField
      control={control}
      name={name}
      render={({ field }) => {
        const { ref: fieldRef, ...restField } = field;
        return (
          <FormItem>
            {label && <FormLabel>{label}</FormLabel>}
            <FormControl>
              <Input
                type={type}
                placeholder={placeholder}
                disabled={disabled}
                ref={mergeRefs(fieldRef, ref)}
                {...restField}
              />
            </FormControl>

            <FormMessage />
          </FormItem>
        );
      }}
    />
  );
}


const RHFInput = forwardRef(RHFInputInner) as <T extends FieldValues>(
  props: RHFInputProps<T> & { ref?: Ref<HTMLInputElement> }
) => React.ReactElement;

export default memo(RHFInput);

FormWrapper.tsx

import type { ReactNode } from "react";
import type {
  DefaultValues,
  FieldValues,
  SubmitHandler,
  UseFormProps,
  UseFormReturn,
} from "react-hook-form";
import { ZodSchema, ZodType } from "zod";

export type FormContext<T extends Record<string, unknown>> =
  UseFormReturn<T> & {
    readOnly: boolean;
  };

export type FormStep<T extends FieldValues> = {
  schema: ZodType<T>;
  content: React.ReactNode;
};

export interface FormWrapperProps<T extends FieldValues> {
  isMultiStep?: boolean;
  mode?: UseFormProps<T>["mode"];
  readOnly?: boolean;
  defaultValues?: DefaultValues<T>;
  children?: ReactNode;
  onSubmit: SubmitHandler<T>;
  steps?: FormStep<T>[];
  submitLabel?: string;
  schema: ZodSchema<T>;
  className?: string;
}

import { memo, useCallback, useState } from "react";
import { isEqual } from "lodash";
import { FormProvider, useForm, type FieldValues } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { cn } from "@/lib/utils";
import { Form } from "@/components/ui/form";
import { Button } from "@/components/ui/button";

const FormWrapper = <T extends FieldValues>({
  isMultiStep,
  mode = "all",
  readOnly = false,
  defaultValues,
  onSubmit,
  steps,
  submitLabel = "Submit",
  schema,
  children,
  className,
}: FormWrapperProps<T>) => {
  const [step, setStep] = useState(0);
  const currentStep = isMultiStep ? steps?.[step] : undefined;

  const currentSchema = isMultiStep ? steps?.[step]?.schema ?? schema : schema;
  const methods = useForm({
    mode,
    defaultValues,
    resolver: zodResolver(currentSchema),
  });

  const extendedForm: FormContext<T> = {
    ...methods,
    readOnly,
  };

  const handleNext = useCallback(async () => {
    const valid = await methods.trigger();
    if (!valid) return;

    setStep((prev) => Math.min(prev + 1, (steps?.length ?? 1) - 1));
  }, [methods, steps]);

  const handlePrev = useCallback(() => {
    setStep((prev) => Math.max(prev - 1, 0));
  }, []);

  const handleFinalSubmit = useCallback(
    (data: T) => {
      onSubmit(data);
    },
    [onSubmit]
  );

  const isFirstStep = step === 0;
  const isLastStep = step === (steps?.length ?? 1) - 1;
  const canGoNext = !isLastStep;
  const canGoPrev = !isFirstStep;

  return (
    <FormProvider {...extendedForm}>
      <Form {...extendedForm}>
        <form
          onSubmit={methods.handleSubmit(handleFinalSubmit)}
          className={cn("space-y-4", className)}
        >
          {isMultiStep ? currentStep?.content : children}
          {isMultiStep ? (
            <div
              className={cn(
                "flex items-center w-full",
                canGoPrev ? "justify-between" : "justify-end"
              )}
            >
              <div>
                {canGoPrev && (
                  <Button
                    type="button"
                    variant="destructive"
                    onClick={handlePrev}
                  >
                    Prev
                  </Button>
                )}
              </div>
              <div className="flex items-center gap-4">
                {canGoNext ? (
                  <Button type="button" onClick={handleNext}>
                    Next
                  </Button>
                ) : (
                  <Button type="submit">{submitLabel}</Button>
                )}
              </div>
            </div>
          ) : (
            <Button type="submit" className="float-right">
              {submitLabel}
            </Button>
          )}
        </form>
      </Form>
    </FormProvider>
  );
};

export default memo(FormWrapper, isEqual);

UserPage.tsx

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import FormWrapper from "@/components/form/form-wrapper";

import RHFInput from "@/components/form/controller/RHFInput";
import { z } from "zod";
import type { FormStep } from "@/components/form/types";


const step1Schema = z.object({
  name: z.string().min(1, "Name is required"),
});
const step2Schema = z.object({
  email: z.string().email("Invalid email"),
});

const mergedSchema = step1Schema.merge(step2Schema);

type FormType = z.infer<typeof mergedSchema>

const steps: FormStep<FormType>[] = [
  {
    schema: step1Schema,
    content: (
      <RHFInput name="name" label="Name" placeholder="Enter your name" />
    ),
  },
  {
    schema: step2Schema,
    content: (
      <RHFInput name="email" label="Email" placeholder="Enter your email" />
    ),
  },
];

const UserPage = () => {
  return (
    <Dialog>
      <DialogTrigger asChild>
        <Button type="button">Create Plan</Button>
      </DialogTrigger>
      <DialogContent className="no-scrollbar">
        <DialogHeader>
          <DialogTitle className="text-start">Create New Plan</DialogTitle>
        </DialogHeader>

        <FormWrapper
          schema={mergedSchema}
          defaultValues={{ name: "", email :""}}
          onSubmit={(data) => console.log("Submitted data", data)}
          isMultiStep
          steps={steps}
        >
         
        </FormWrapper>
      </DialogContent>
    </Dialog>
  );
};

export default UserPage;

no return value for function in array.push(function())

Question:
I have two cases where function pushing an item to an array returns no value—one returns null, and the other does not. Why?

Over-view:
Flow of the click handler:

Button click
Triggers the push (or seat) function.

Inside the function, three cases:
i. Add seat
• Seat isn’t in arr && arr.length < 5
• → Push the seat and return its coordinates.

ii. Too many seats
• Seat isn’t in arr && arr.length >= 5
• → Show an alert(‘only 5 seats…’) and return nothing (undefined).

iii. Remove seat
• Seat is in arr
• → Filter it out of arr and return nothing (undefined).

Error: As written in both alert and delist cases, the return value is missing. However, when case 3 (delist) runs, no extra item is added to the array, while case 2 (alert) adds a null item

full-Code for reference:

import './App.css'

function App() {
  var arr = []
  function seat(m, e) {
    var ini;
    var col = m % 5
    var row = Math.floor(m / 5) //why is ceil 0?

    const val = arr.some((i,ind) => {if(JSON.stringify(i) == JSON.stringify([row + 1, col + 1])){ini=ind} return (JSON.stringify(i) == JSON.stringify([row + 1, col + 1])) })

    console.log(JSON.stringify(arr)+'i am 1')
    if (!val) {
      console.log(JSON.stringify(arr)+'i am 2')
      if(arr.length<5){
        e.target.style.backgroundColor != "red" ? e.target.style.backgroundColor = "red" : e.target.style.backgroundColor = "#16a34a"
      return ([row + 1, col + 1])}
      else{
        alert('only 5 seats can be selected at once. de-selct some to add new')
      }
    }
    else{
      arr=arr.filter((_,i)=>{return (i!=ini)})
      e.target.style.backgroundColor != "red" ? e.target.style.backgroundColor = "red" : e.target.style.backgroundColor = "#16a34a"
      console.log(JSON.stringify(arr)+'i am 3')
    }
  }
 
  function buy() {
    alert(`you are buying seats:${JSON.stringify(arr)}`)
  }
  return (
    <>
      <div className='w-[100vw] h-[100vh] bg-black flex justify-center items-center'>
        <div className='bg-amber-50 w-[75vw] flex items-center flex-col gap-[40px]'>
          <div className='w-[100%] text-center mt-[6vh] text-3xl '>VVIP corner</div>
          <div className='vip w-[100%]'>
            {Array(25).fill('').map((_, i) => { return (<div key={i} className='bg-green-600 text-amber-50 text-center flex justify-center items-center h-[7vh] min-h-fit min-w-fit' onClick={(e) => { arr.push(seat(i, e)); }}>{i + 1}</div>) })}/* **arr.push(seat(i, e)):our error function***/
          </div>
          <button className='w-[15vw] bg-black text-amber-50 text-center rounded-3xl m-[10px]' onClick={buy}>BUY</button>
        </div>
      </div>
    </>
  )
}

export default App

op-1: add; op-2:alert when array is full; op-3: de-list
Console.log(array) when after 5 item user try to list 6 item and alert execute[NULL-ITEM ADDED]:
Console.log(array) when after 5 item user try to list 6 item and alert execute[NULL-ITEM ADDED]
Console.log(array) when user de-list and list continuously same item [NO NULL-ITEM ADDED]:
Console.log(array) when user de-list and list continuously same item [NO NULL-ITEM ADDED]

Expectation:
I understand why both return null, but only one adds null to the array. I’d like to know the reason for this behavior.

Fetch to PHP endpoint returns 404 and blank response—even though .php exists.(jsh2) [closed]

I’m building a simple single‐page app that should fetch tablet data from a PHP/MySQL backend. Here are my files:
connection

<?php
$servername="localhost";
$username="root";
$password="";
$database="tabla neve";
$conn = new mysqli(
    $srevername,
    $username,
    $password,
    $database
);

Adatok

<?php
header("Content-type: application/json; charset=utf-8");

require_once "connection.php";

$sql = "SELECT * FROM tabletek;";
$result = mysqli_query($conn, $sql);

$data = [];

if ($result && mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = array(
            "kep" => $row['kep'],
            "gyarto" => $row['gyarto'],
            "operacios_rendszer" => $row['operacios_rendszer'],
            "ar" => $row['ar'],
        );
    }
    http_response_code(200);
    echo json_encode($data);
} else {
    http_response_code(404);
    echo json_encode(["message" => "Nincsenek elérhető adatok."]);
}
?>

html

<!DOCTYPE html>
<html lang="hu">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vizsga Feladat</title>
    <link rel="stylesheet" href="css.css">
    <script src="json.js"></script>
</head>
<body>
    <div class="fejlec"><p>Tablet Bolt</p></div>
    <div id="container">
        <div class="navbar">
            <a href="#home" class="elso">Készülékek</a>
            <a href="#news" class="masodik">Rólunk</a>
            <a href="#elerhetoseg" class="harmadik">Elérhetőségeink</a>
            <div class="dropdown">
              <button class="dropbtn">M
                <i class="fa fa-caret-down"></i>
              </button>
              <div class="dropdown-content">
                <a href="#">Készülékek</a>
                <a href="#">Rólunk</a>
                <a href="#">Elérhetőségeink</a>
              </div>
            </div>
          </div>
</body>
</html>

json.js

document.addEventListener("DOMContentLoaded", () => {

  const container = document.getElementById("container");

  fetch('adatok.php')

    .then(response => {

      if (!response.ok) {
        throw new Error('Hálózati hiba: ' + response.status);
      }

      return response.json();
    })

    .then(data => {

      console.log("Kapott adatok:", data);

      data.forEach(tablet => {

        const div = document.createElement("div");

        div.classList.add("doboz1");

        div.innerHTML = 
          <img src="${tablet.kep}" >
          <div class="Leírás1">
            <h3>${tablet.gyarto}</h3>
            <div class="szoveg1">
              <p>OS: ${tablet.operacios_rendszer}</p>
              <p>Ár: ${tablet.ar} Ft</p>
            </div>
          </div>
        ;

        container.appendChild(div);
      });
    })

    .catch(error => {

      console.error('Hiba történt:', error);
    });
});

// A maradék két lekérdezés ugyanúgy működhet, csak más PHP-végpontokat adsz meg fetch-ben: pl. fetch('elerhetoseg.php')

// Opció: jQuery-vel a navigáció animált elrejtéséhez/megjelenítéséhez

// $(document).ready(function () {
//     // Várja, hogy az egész oldal betöltődjön jQuery-vel

//     $(".elso").click(function (e) {
//         // Ha az első menüpontot kattintják
//         $(".masodik").hide();   // Elrejti a második menüpont tartalmát
//         $(".harmadik").hide();  // Elrejti a harmadik menüpont tartalmát
//         $(".elso").show();      // Megjeleníti az első menüpont tartalmát
//     });

//     $(".masodik").click(function (e){
//         // Ha a második menüpontot kattintják
//         $(".elso").hide();
//         $(".harmadik").hide();
//         $(".masodik").show();
//     });

//     $(".harmadik").click(function (e) {
//         // Ha a harmadik menüpontot kattintják
//         $(".elso").hide();
//         $(".masodik").hide();
//         $(".harmadik").show();
//     });
// });

Problem:

In the browser console I always see:

Fetch error: Error: Network error: 404

Navigating directly to adatok.php in my browser shows a completely blank page (no JSON, no PHP errors).

I suspect the typo in connection.php ($srevername vs. $servername) is causing a fatal error that’s not displayed.

Questions:

How can I enable PHP error reporting (or otherwise surface fatal parse/runtime errors) so that adatok.php doesn’t fail silently?

What’s the recommended way to structure a PHP/MySQL JSON API so that it always returns a well-formed JSON object (even on errors) and correct HTTP status codes (200, 4xx, 5xx)?

When debugging a failed Fetch API call, what are the quickest ways to inspect the raw HTTP response (status, headers, body) in browser devtools?

Is it better to use response.text() instead of response.json() when first debugging malformed or empty responses?

Any other common pitfalls (CORS, file permissions, missing defer on , directory layout) that could produce a 404 even when the .php file exists?

Thanks in advance for any pointers on uncovering these silent failures and returning proper JSON to my frontend!

How do I fix error message ‘Failed to execute ‘createObjectURL’ on ‘URL’: Overload resolution failed’

I currently have the below JS code – I’m trying to make the image that’s uploaded into my HTML upload box appear in the box once it’s been uploaded by the user, but I keep getting an error message. The error message is:

Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.
const dropArea = document.getElementById("drop-area");
const inputFile = document.getElementById("input-file");
const imageView = document.getElementById("img-view");

inputFile.addEventListener("change", uploadImage);

function uploadImage() {
  let imgLink = URL.createObjectURL(inputFile.files[0]);
  imageView.style.backgroundImage = `url${imgLink}`;
}

HTML for reference:

  <form class="tg-form">
    <div>Upload Avatar</div>
    <div class="upload-container">
      <label for="input-file" id="drop-area">
        <input type="file" accept="image/*" id="input-file" hidden />
        <div class="inner-label-container">
          <div id="img-view">
            <img src="assets/images/icon-upload.svg" />
          </div>
          <div>Drag and drop or click to upload</div>
        </div>
      </label>
    </div>

How to fix this?

How to find the original Instagram post using asset_id received from webhook?

We are using Instagram’s Graph API and have implemented a webhook to listen for media shared in Direct messages. When someone shares a post via Direct, the webhook sends us an event payload that contains only an asset_id (e.g., a CDN media identifier).

However, we are unable to find a way to map this asset_id back to the original post (i.e., the media object or permalink on Instagram). We’ve looked through the Instagram Graph API documentation but couldn’t find a way to resolve an asset_id to a media ID or any useful metadata.

What we have:

A webhook event triggered when a user shares a post via Direct message.

The payload includes something like: “asset_id”: “17890012345678901”

What we want:

Find the original post ID or permalink using the asset_id.

What we’ve tried:

Searching through Instagram Graph API endpoints with media IDs and user tokens.

Checking if asset_id is queryable via /media or /media/{media-id}.

Looking for debugging tools or mappings via Meta for Developers portal.

Is there any way to reverse-lookup or resolve an asset_id to its corresponding Instagram post using Instagram Graph API or other official tools?

What is function of var in javascript [closed]

when I write this code answer wilL be 3,

Var gameLevel=1;
Var gameLevel=2;
 Var gameLevel=3;
alert("your game level is: " + gameLevel);

and when I write same problem without Var then again answer same,

Var gameLevel=1;
gameLevel=2;
gameLevel=3;
alert("your game level is: " + gameLevel);

can anyone answered me what has been happening here?

Why is my array passing the contains constraint in my JSON schema?

I am testing a schema (draft 2020-12) and data with the JSON Schema validator and I am wondering why the data is valid.
The test succeeds because the “contains” property is satisfied.

But when I am trying to invalidate the data with the first item of the first nested arrays, the test still succeeds because the item is not counted. Shouldn’t it be counted?

It is counted when both string have 5 chars and then the test fails, but not if only one string has 5 chars as below.

Below the schema and the data that passes the test and fails when all strings have 5 characters. Shouldn’t it fail now as 3 strings have 5 characters?

{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "properties": {
        "array": {
            "type": "array",
            "items": {
                "items": {
                    "items": {
                        "properties": {
                            "c": {
                                "properties": {
                                    "d": {
                                        "maxLength": 6,
                                        "type": "string"
                                    }
                                },
                                "type": "object"
                            }
                        },
                        "type": "object"
                    },
                    "type": "array"
                },
                "type": "array"
            },
            "maxContains": 2,
            "contains": {
                "items": {
                    "items": {
                        "properties": {
                            "c": {
                                "properties": {
                                    "d": {
                                        "minLength": 5,
                                        "type": "string"
                                    }
                                },
                                "type": "object"
                            }
                        },
                        "type": "object"
                    },
                    "type": "array"
                },
                "type": "array"
            }
        }
    },
    "type": "object"
}
[
    [
        [
            {
                "c": {
                    "d": "abcd"
                }
            }
        ],
        [
            {
                "c": {
                    "d": "abcde"
                }
            }
        ]
    ],
    [
        [
            {
                "c": {
                    "d": "abcde"
                }
            }
        ]
    ],
    [
        [
            {
                "c": {
                    "d": "abcde"
                }
            }
        ]
    ]
]

Par où commencé dans le développement back-end? [closed]

Bonjour,

je suis en pleine reconversion professionnel et j’aimerais m’orienté vers le développement back-end. J’ai 22ans et je suis cariste magasinier de base donc rien avoir et j’ai un bac pro dans la menuiserie. J’avais aucune connaissance en informatique avant de vraiment m’informé et de ce fait, je ne sais pas vraiment par où commencé. Je sais toujours pas quel langage choisir, java, python, javascript ou autre. En sachant que je suis en autodidacte et que je compte utilisé l’ia copilot comme mentor quand je serais bloqué. Si vous pouvais m’aidé avec une roadmap et m’aidé à choisir un langage je vous serais très reconnaissant

Prevent null prop value in Vue 3.X

Defining the optional prop, although we may want to unify the undefined and null to something one, user can pass any of undefined or null.

If user will specify null, Vue will not emit any warnings because Vue considers the null as optional value:

// === vue-facing-decorators version
import {
  ComponentBase as VueComponentConfiguration,
  Vue as VueComponent,
  Prop as VueProperty,
} from "vue-facing-decorator";

@VueComponentConfiguration({ name: "Button" })
class Button extends VueComponent {

  @VueProperty({ type: String })
  protected readonly label?: string | null;

}
 
// === Vue options API version
export default {
  props: {
    label: {
      type: String,
      required: false
    }
  }
};

The isNonEmptyString will not prevent the null because Vue will recognize the null as omitted property and will not execute the validator:

import { isNonEmptyString } from "@yamato-daiwa/es-extensions";


// === vue-facing-decorators version
@VueComponentConfiguration({ name: "Button" })
class Button extends VueComponent {

  @VueProperty({ validator: isNonEmptyString })
  protected readonly label?: string | null;

}


// === Vue options API version
export default {
  props: {
    label: {
      validator: isNonEmptyString,
      required: false
    }
  }
};

But if Vue considers the null as omitted property, why it does not substitute it when default specified?!

import { isNonEmptyString } from "@yamato-daiwa/es-extensions";


// === vue-facing-decorators version
@VueComponentConfiguration({ name: "Button" })
class Button extends VueComponent {

  @VueProperty({ type: [ String, Array ], default: (): ReadonlyArray<string> => [] })
  protected readonly mainSlotWrapperAdditionalCSS_Classes!: ReadonlyArray<string> | string | null;


}

// === Vue options API version
export default {
  props: {
    mainSlotWrapperAdditionalCSS_Classes: {
      type: [String, Array],
      default: () => []
    }
  }
};

So, no way to prevent the null? We need to check each optional prop for both undefined and null or write the computed for these props? Too many routines for 202Xs, I want something more cleaner but doing all of this works.

You should use the TypeScript!!!

I am using, but TypeScirpt is NOT the solution of this problem because it works before executing of the script while Vue’s validation at the time of script execution. Same about React’s prop-types which has been deprecated as if TypeScript will validate props during the script execution instead.

The checking of the props during the script execution is important because:

  1. Component user could use JavaScript instead of TypeScript
  2. I know that in average company the development is executed chaotically with tens of TypeScript errors, even the notification of TypeScript has not been set well.

How to resolve barcode scanner promblem in web?

I have a problem with my web source code. I have made sure that the site is accessed via https and camera access permission is granted. However, the barcode scan display does not appear and only displays a white blank. I tried to access it via chrome on android.

This is my code

    <?php
$satuan_list = ['pcs', 'dus', 'pack', 'ball', 'renteng'];
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Form Input Barang</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    video {
      width: 100%;
      height: auto;
    }
  </style>
</head>
<body class="bg-light py-4">
<div class="container">
  <h2 class="text-center mb-4">Form Input Barang</h2>

  <form action="save_barang.php" method="POST" enctype="multipart/form-data" class="bg-white p-4 rounded shadow">
    <div class="mb-3">
      <label class="form-label">Nama Barang</label>
      <input type="text" name="nama_barang" class="form-control" required>
    </div>

    <div class="mb-3">
      <label class="form-label">Kode Gudang</label>
      <input type="text" name="kode_gudang" class="form-control" required>
    </div>

    <div class="mb-3">
      <label class="form-label">Vendor Penyedia</label>
      <input type="text" name="vendor" class="form-control" required>
    </div>

    <div class="mb-4">
      <label class="form-label">Foto Barang</label>
      <input type="file" name="foto" class="form-control" accept="image/*" capture="environment">
    </div>

    <?php foreach ($satuan_list as $satuan): ?>
    <div class="border rounded p-3 mb-4">
      <h5 class="mb-3">Satuan: <?= ucfirst($satuan) ?></h5>
      <input type="hidden" name="satuan[]" value="<?= $satuan ?>">

      <div class="row g-3">
        <div class="col-md-4">
          <label class="form-label">Stok (<?= $satuan ?>)</label>
          <input type="number" name="stok_<?= $satuan ?>" class="form-control">
        </div>

        <div class="col-md-4">
          <label class="form-label d-flex justify-content-between">
            <span>Barcode (<?= $satuan ?>)</span>
            <button type="button" class="btn btn-sm btn-outline-primary" onclick="startScanner('barcode_<?= $satuan ?>')">Scan</button>
          </label>
          <input type="text" name="barcode_<?= $satuan ?>" id="barcode_<?= $satuan ?>" class="form-control barcode-input">
        </div>

        <div class="col-md-4">
          <label class="form-label">Harga Eceran</label>
          <div class="input-group">
            <span class="input-group-text">Rp.</span>
            <input type="number" step="0.01" name="harga_eceran_<?= $satuan ?>" class="form-control">
          </div>
        </div>

        <div class="col-md-4">
          <label class="form-label">Harga Grosir</label>
          <div class="input-group">
            <span class="input-group-text">Rp.</span>
            <input type="number" step="0.01" name="harga_grosir_<?= $satuan ?>" class="form-control">
          </div>
        </div>

        <div class="col-md-4">
          <label class="form-label">Min. Pembelian Harga Grosir</label>
          <input type="number" name="min_grosir_<?= $satuan ?>" class="form-control">
        </div>

        <?php if ($satuan != 'pcs'): ?>
        <div class="col-md-4">
          <label class="form-label">Isi per <?= $satuan ?> (pcs)</label>
          <input type="number" name="isi_per_pcs_<?= $satuan ?>" class="form-control">
        </div>
        <?php endif; ?>
      </div>
    </div>
    <?php endforeach; ?>

    <div class="d-grid gap-2">
      <button type="submit" class="btn btn-primary">Simpan Barang</button>
      <a href="list_barang.php" class="btn btn-secondary">Lihat Daftar Barang</a>
    </div>
  </form>

  <!-- Modal Scanner -->
  <div class="modal fade" id="scannerModal" tabindex="-1" aria-labelledby="scannerModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Scan Barcode</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup" onclick="stopScanner()"></button>
        </div>
        <div class="modal-body">
          <video id="preview" autoplay muted playsinline style="width: 100%; border: 1px solid #ccc; border-radius: .5rem;"></video>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" data-bs-dismiss="modal" onclick="stopScanner()">Tutup</button>
        </div>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://unpkg.com/@ericblade/[email protected]/dist/quagga.min.js"></script>

<script>
let activeInput = null;
const scannerModal = new bootstrap.Modal(document.getElementById('scannerModal'));

function startScanner(inputId) {
  activeInput = document.getElementById(inputId);
  scannerModal.show();

  if (Quagga.running) {
    Quagga.stop();
  }

  console.log("Mulai inisialisasi scanner...");

  Quagga.init({
    inputStream: {
      type: "LiveStream",
      constraints: {
        facingMode: "environment"
      },
      target: document.querySelector('#preview')
    },
    decoder: {
      readers: ["ean_reader", "code_128_reader", "upc_reader"]
    }
  }, function(err) {
    if (err) {
      console.error("Gagal inisialisasi Quagga:", err);
      alert("Tidak bisa akses kamera: " + err.message);
      return;
    }
    console.log("Scanner berhasil dijalankan!");
    Quagga.start();
  });
}

function stopScanner() {
  if (Quagga.running) {
    Quagga.stop();
  }
}

Quagga.onDetected(result => {
  if (!result || !result.codeResult || !result.codeResult.code) return;

  const code = result.codeResult.code;
  if (activeInput) {
    activeInput.value = code;
    stopScanner();
    scannerModal.hide();
  }
});
</script>
</body>
</html>

and I also attached the display via the Android Chrome webbarcode visual

How can I return the max values and the keys from an object in Javascript?

I’m trying to build a function that takes a string as a parameter and return the character or characters that appear the most in the that string.
I have tried the code below but it only returns an array with the keys. I want to return someone like that: e appears 4 times and b appears 4 times in case both of them have the max value.

Below is my code and how I started:

const frequentChar = str =>{
    let count = {}
    for(let char of str.replace(/s/g, '')){
        if(count[char]){
            count[char] +=1
        }else{
            count[char] = 1
        }
    }
    const result = Object.keys(count).filter(x => {
        return count[x] == Math.max.apply(null, Object.values(count));
    });
    console.log(result);
}
frequentChar(text)

How to refetch from a client component with useQuery

I have a client component that fetches the list of project and a dialog box that creates a project but I cant update the project list unless I have to do a manual refresh on the browser.

The flow is:

  1. navigating to project page should fetch the project list. (working)
  2. submitting the dialog form should create a project. (working)
  3. after submitting dialog should close. (working)
  4. after closing the dialog box, it should refetch or query the project page again. (not working)

solutions that Ive tried:

  1. calling revalidatePath('/projects') this wont work because the project page is client component.
  2. calling redirect('/projects') (I don’t know why).
  3. tried calling window.location.reload(): inside the server component won’t work to.

project page code:

"use client";

import React from "react";
import {DataTable} from "./dataTable";
import {columns} from "./columns";
import {getProjectLists} from "@/app/api/projectActions";
import {useQuery} from "@tanstack/react-query";
import {Button} from "@/components/ui/button";

const ProjectPage = () => {
  const {data, isError, isLoading, error, isSuccess} = useQuery({
    queryKey: ["projects"],
    queryFn: () => getProjectLists(1, 10),
  });

  console.log("data", data);

  if (isLoading) {
    return <div className="text-center">Loading...</div>;
  }

  return (
    <div className="w-4/5 mx-auto py-10">
      {data && <DataTable columns={columns} data={data} />}
      <Button>
        {/* (This should something like infinite scroll. check react-query for code) */}
        Load More
      </Button>
    </div>
  );
};

export default ProjectPage;

I’m still new to react-query so I don’t have a clue. I tried using the refetch method won’t work it will do a infinite call.

this wont work

if(isSuccess) {
 refetch();
}

I’m not sure if I’m missing something on react-query.

GET App Route doesn’t get URL params in NextJS

I have an API APP route

app/api/resthistoryserv/route.ts [folder structure]

The call is being made like this:

const res = await fetch(
          `/api/resthistoryserv?client_id=ASDFASFDDFASD')}`
        );

/api/resthistoryserv?client_id=ASDFASFDDFASD

The call goes through but it doesn’t have the query params.

App route code:

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    console.log('nextUrl:', request.nextUrl);
    console.log('All received parameters:',   Object.fromEntries(searchParams.entries()));

    console.log('CLIENTID', searchParams.get('client_id'));
.....
}

This is what comes back when I try to print them:

nextUrl: NextURL {
  [Symbol(NextURLInternal)]: {
    url: URL {
      href: 'https://localhost:3000/api/resthistoryserv',
      origin: 'https://localhost:3000',
      protocol: 'https:',
      username: '',
      password: '',
      host: 'localhost:3000',
      hostname: 'localhost',
      port: '3000',
      pathname: '/api/resthistoryserv',
      search: '',
      searchParams: URLSearchParams {},
      hash: ''
    },
    options: { headers: [Object], nextConfig: undefined },
    basePath: '',
    domainLocale: undefined,
    defaultLocale: undefined,
    buildId: undefined,
    locale: undefined,
    trailingSlash: false
  }
}
All received parameters: {}
CLIENT ID null

React Ag Grid tables not rendering at all

I had multiple ag grid tables rendering on different pages, but the the rows weren’t loading at one point and it just said “loading” in the table. I reloaded the page and now no tables on any of my pages are there at all, not even the box.

Here’s a picture just for clarification:
Here's a picture just for clarification

I made a copy of the code with everything simplified way down and it still doesn’t render, here’s my simplified code.

import React from 'react'
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';

const Kanban = () => {
  return (
    <div className="ag-theme-alpine" style={{ height: 500, width: 1000}}>
      <AgGridReact rowData={{'a':'b'}} columnDefs={{field:'a'}}/>
    </div>
  )
}

export default Kanban