Search code examples
reactjsreact-hooksuse-effectuse-state

Type Error : destroy is not a function in Reactjs while call api async function in useEffect hook



const [dailyData, setDailyData] = useState([]);
 useEffect(async () => {
    const fetchData =  await fetchDailyData();  // fetchDailyData() is calling Api 
    setDailyData(fetchData); 

    console.log(fetchData); //fetchData print the value but dailyData not updating


  },[]);

showing destroy is not a function and func.apply is not a function


Solution

  • Effect hook callbacks can't be async. Instead, declare a callback function scoped async function and then invoke it. Also, as pointed out by @StéphaneVeyret your "async" effect hook callback implicitly returns a Promise which gets interpreted as an effect hook clean up function. It isn't one though and causes error.

    useEffect(() => {
      const asyncFetchDailyData = async () => {
        const fetchData = await fetchDailyData(); // fetchDailyData() is calling Api 
        setDailyData(fetchData);
        console.log(fetchData);
      }
    
      asyncFetchDailyData();
    }, []);