Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

276
Visualizações
How to Generate a Unique Id Global Variable that updates after event? React.js, React Router

I have a React Router App with multiple Routes. I need a component that will generate an Id number onSubmit. A unique Id needs to be assigned to each submission. This component needs to be imported into multiple pages and the count needs to be consistent across these pages. The value of the variable uniqueId is updating within the component but the value of the same variable imported into the page with handleSubmit remains constant with it's initial value which makes sense but I need to be able to access the updated value of uniqueId from within each page. Is it possible to have a global variable across multiple React Router pages?

I appreciate all ideas! Thank you for your time!

import react, from 'react';
import './pages.css';

let uniqueId = 0;

export function GenId(){
  uniqueId++;
  console.log(uniqueId);
}

export default uniqueId;

handleSubmit:

import { GenId } from './genIds';
import uniqueId from './genIds';

const handleSubmit = (event) => { 
  event.preventDefault();
  toggleDisabled();
  GenId();
  console.log(uniqueId)
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can create a generator function to increment and return a counter value.

Example:

genId.js

function* numericalIdGenerator(seed = Date.now()) {
  while (true) yield seed++;
}

const generateNumericalId = numericalIdGenerator();

export const genId = () => generateNumericalId.next().value;

It uses Date.now() as a default starting seed value to avoid id collisions with previously generated ids, but you can use any starting number you like.

Usage:

import { genId } from "./genId";

...

const handleSubmit = (event) => {
  event.preventDefault();
  const uniqueId = genId();
  console.log({ uniqueId });
};

Edit how-to-generate-a-unique-id-global-variable-that-updates-after-event-react-js

enter image description here

Example Test Code:

import { genId } from "./genId";

const ComponentA = () => {
  const handleSubmit = (event) => {
    event.preventDefault();
    const uniqueId = genId();
    console.log("ComponentA", { uniqueId });
  };

  return (
    <form onSubmit={handleSubmit}>
      <h1>Form A</h1>
      <button type="submit">Submit</button>
    </form>
  );
};

const ComponentB = () => {
  const handleSubmit = (event) => {
    event.preventDefault();
    const uniqueId = genId();
    console.log("ComponentB", { uniqueId });
  };

  return (
    <form onSubmit={handleSubmit}>
      <h1>Form b</h1>
      <button type="submit">Submit</button>
    </form>
  );
};

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <ComponentA />
      <ComponentB />
    </div>
  );
}

Suggestion

The above solution only provides/guarantees uniqueness with a single app instance. If you are submitting data to some external repository then the suggestion would be to use a utility that provides truly global and unique ids, e.g. GUIDs. One such package I (and @ChrisHamilton) recommend is uuid. Its usage is nearly identical.

Example:

import { v4 as uuidV4 } from "uuid";

...

const handleSubmit = (event) => {
  event.preventDefault();
  const uniqueId = uuidV4();
  console.log({ uniqueId });
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda