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?
CodePudding user response:
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>
CodePudding user response:
<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>