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

Viewed 4201

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

2 Answers

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();
}, []);

useEffect(async () => { //in this part the async is the wrong

instead of that you can create a function async inside of useEffect

useEffect(() => {
  const asyncFetchDailyData = async () => {
  ...
  }

  asyncFetchDailyData();
}, []);
Related