3

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

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Naveen kumar
  • 33
  • 2
  • 4
  • _fetchData print the value but dailyData not updating_ `setDailyData` will update the state asynchronously, you can't log `dailyData` immediately after calling `setDailyData` – Yousaf May 31 '20 at 07:48
  • can you share fetchDailyData ? – Bahtiyar May 31 '20 at 07:50

2 Answers2

9

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();
}, []);
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • 1
    Just to add information: an asynchronous function will always return a result as a `Promise`. When calling `useEffect` react expects the function result, if any, to be a function which will be called to “clean” the effect. So the error. – Stéphane Veyret May 31 '20 at 08:07
  • Thank you! I had an async useEffect in next.js and the error message showed in an unrelated spot, you've saved me some hours. – Evgeny Jan 15 '21 at 19:45
0

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();
}, []);
rnewed_user
  • 1,386
  • 7
  • 13