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

124
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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