Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

123
Vistas
Call a function inside a function and return a value

Is it possible to call a function on click a button, execute some code like adding an item to a database and also having access to a variable that was created in that function?

For example,

const handleAddToDb = () => {
  let id = 123423r //note the ID is auto generated each time this function is called
   addToDb()
   return id
}
<button onClick={()=> {
  handleAddToDb()
}}>Click</button>
console.log(id???) //any idea how to acheive this?
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

<body>
    <button onclick="
            handleAddToDb()
    ">
    Click me
    </button>
</body>
<script>
    // let id is a global variable
    let id = 10;
    const handleAddToDb = () => {
        addToDb()
        console.log(id)
    }
    function addToDb(){
        id++;
    }
    console.log(id) //any idea how to acheive this?
</script>

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could have your click handler return the id (as you're doing) and assign it to a variable that's accessible in your outer scope.

You could also establish a "store" that's responsible for managing all of the data, including doing the add and keeping track of the new id. See snippet below for a very skeletal example of how two separate buttons can access the same data using this approach.

const addButton = document.getElementById('add');
const logButton = document.getElementById('log');

class Store {
  lastId = 0;
  
  add() {
    // do whatever you need to do.
    // increment and return the id.
    return this.lastId++;
  }
}

const store = new Store();

addButton.addEventListener('click', () => {
  store.add();
  console.log(store.lastId);
})

logButton.addEventListener('click', () => {
  console.log(store.lastId);
})
<button id="add">Add</button>

<button id="log">Log Last Id</button>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda