I am going to call async function in onclick
event in button. But it is not working. Is it possible to call the async function inside button onlick ?
Here is the code.
Filter button
const FilterButton = (props) => {
return (
<div className="p-2 ">
<button className="btn btn-secondary" onClick={props.fetchInvoices}>Filter</button>
</div>
);
};
fetchInvoices async function
fetchInvoices = async () => {
const invoices = await getInvoices(this.currentState.params);
this.props.store.dispatch(UpdateInvoices(invoices));
};
code to pass function to component
<SearchField store = {this.props.store} fetchInvoices={this.fetchInvoices}/>
Example: Call a Function After Clicking a Buttonimport React from 'react'; function App() { function sayHello() { alert('Hello!' ); } return ( <button onClick={sayHello}> Click me! </button> ); } export default App; The simple App component above has one function called sayHello(), and a single button.
The React onClick event handler enables you to call a function and trigger an action when a user clicks an element, such as a button, in your app. Event names are written in camelCase, so the onclick event is written as onClick in a React app. In addition, React event handlers appear inside curly braces.
The first solution to perform multiple onClick events in React is to include all of your actions inside of a function and then call that single function from the onClick event handler. Let's explore how to do that in a React Component: import React from 'react'; function App() { function greeting() { console.
This is how I call my asyncs inside an onClick
:
<Button onClick={async () => {await this.asyncFunc("Example");} }/>
async asyncFunc(text) {
console.log(text);
}
Your async function:
const asyncFunc = async () => {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("I am a done promise!"), 3000)
});
let result = await promise
alert(result);
}
Your button component call:
<button onClick={asyncFunc} >I am a button!</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With