Home > Blockchain >  ReactJS: How do you call an async fuction on button click?
ReactJS: How do you call an async fuction on button click?

Time:05-04

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;

                                                                                                                   

CodePudding user response:

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

CodePudding user response:

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;

CodePudding user response:

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;
        
                                
  • Related