Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
ReactJS: How do you call an async fuction on button click?

How can I call fetchData() on button a click ? Should i call the fucntion using useEffect ?

function Subscriptions() {
  const [allUsers] = useState([]);
  useEffect(() => {
    fetchData = async () => {
      try {
       // some code
      } catch (err) {
        console.log(err);
      }
    };
  }, []);
  return (

<Button onclick={fetchData()}>Fetch Data</Button>

);
}
export default Subscriptions;

                                                                                                                   
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

fetchData is in a different nested scope and therefore not accessible to the button component. Use useCallback to define an async callback:

import React, { useState, useCallback } from "react";

function Subscriptions() {
  const [allUsers] = useState([]);
  const fetchData = useCallback(async () => {
    try {
      // some code
    } catch (err) {
      console.log(err);
    }
  }, []);
  return <Button onClick={fetchData}>Fetch Data</Button>;
}
export default Subscriptions;
about 4 years ago · Juan Pablo Isaza Report

0

useEffect hook called at load time . you should define fetchData function outside of useEffect actually you dont need useEffect for this situation

about 4 years ago · Juan Pablo Isaza Report

0

You have to make a function then call on both times in useEffect as well as onClick.

function Subscriptions() {
      const [allUsers] = useState([]);
      const fetchData = async () => {
         try {
           // some code
         } catch (err) {
            console.log(err);
         }
      };      
     useEffect(() => {
      fetchData()
     }, []);
      return (
        <Button onclick={()=>fetchData()}>Fetch Data</Button>
      );
    }
    export default Subscriptions;
        
                                
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!