Home > Mobile >  React Hook UseEffect cannot be called at the top level
React Hook UseEffect cannot be called at the top level

Time:10-03

I am getting this same error whether I use useEffect inside of my function component or out of it:

React Hook "useEffect" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function

 import React, { useEffect } from "react";
    
const GetVerse = async () => {
  useEffect(async () => {
    const fetchVerse = await fetch(
      "https://bhagavad-gita3.p.rapidapi.com/v2/chapters/1/verses/null/"
    );
    const verseBody = await fetchVerse.json();
    console.log(verseBody);
  });
  return <div></div>;
};

export default GetVerse;

CodePudding user response:

You component can't be async. But if you want to have an async useEffect, you have to do like this :

const GetVerse = () => { // component can't be async

  useEffect(() => { // useEffect callback can't be async either
    const fn = async () => { // declare an async function here
      const fetchVerse = await fetch(url)
      const verseBody = await fetchVerse.json()
      console.log(verseBody);
    }

    fn() // call the async function
  }, []) // don't forget to add dependency array here

  return <div></div>
}

CodePudding user response:

React Components and the useEfffect callback shouldn't be async. Here is a way to use await in the callback. The idea is to create a async function and then call it. Also consider adding an empty array [] as the second parameter to useEffect as not putting this will cause infinite API calls.

import React, { useEffect } from "react";

const GetVerse = () => {
  useEffect(() => {
    async function getData() {
      const fetchVerse = await fetch(
        "https://bhagavad-gita3.p.rapidapi.com/v2/chapters/1/verses/null/"
      );
      const verseBody = await fetchVerse.json();
      console.log(verseBody);
    }
    getData();
  }, []);
  return <div></div>;
};

export default GetVerse;

  • Related