Je vais appeler la fonction asynchrone dans l'événement onclick dans le bouton. Mais ça ne fonctionne pas. Est-il possible d'appeler la fonction async à l'intérieur du bouton onlick?
Voici le code.
Bouton Filtrer
<SearchField store = {this.props.store} fetchInvoices={this.fetchInvoices}/>
Fonction asynchrone fetchInvoices
fetchInvoices = async () => {
const invoices = await getInvoices(this.currentState.params);
this.props.store.dispatch(UpdateInvoices(invoices));
};
code pour passer la fonction au composant
const FilterButton = (props) => {
return (
<div className="p-2 ">
<button className="btn btn-secondary" onClick={props.fetchInvoices}>Filter</button>
</div>
);
};
3 Réponses :
Essayez ceci
<button className="btn btn-secondary" onClick={props.fetchInvoices}>Filter</button>
au lieu de
<button className="btn btn-secondary" onClick={()=>props.fetchInvoices()}>Filter</button>
À la place, essayez de faire
<button className="btn btn-secondary" onClick={this.handleFetchInvoices}>Filter</button>
handleFetchInvoices(){
this.props.fetchInvoices
}
Cela ne fait rien. Ce devrait être: handleFetchInvoices () {this.props.fetchInvoices (); }
C'est ainsi que j'appelle mes asynchrones dans un onClick :
<Button onClick={async () => {await this.asyncFunc("Example");} }/>
async asyncFunc(text) {
console.log(text);
}
Je pense que c'est exactement la même chose que:
Cela ne sert à rien. Le délégué Async est exécuté sans attendre son résultat.
Ça va marcher. Quelle est l'erreur?
Maintenant ça marche. Cette fetchInvoice dans SeachField est passée en paramètre. J'ai ajouté fetchInvoices = {this.fetchInvoices} à la place fetchInvoices = {this.props.fetchInvoices}