Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can async functions be called in onClick in button react

Tags:

reactjs

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}/>
like image 946
Pubudu Jayasanka Avatar asked Feb 20 '19 05:02

Pubudu Jayasanka


People also ask

How do you call a function on React onClick?

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.

Can we call component on onClick in React?

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.

Can onClick have multiple functions React?

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.


2 Answers

This is how I call my asyncs inside an onClick:

<Button onClick={async () => {await this.asyncFunc("Example");} }/>

async asyncFunc(text) {
    console.log(text);
}
like image 193
Moritz Schmidt Avatar answered Oct 18 '22 05:10

Moritz Schmidt


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>
like image 38
Sean Avatar answered Oct 18 '22 05:10

Sean