Search code examples
reactjsfetchuse-effect

Getting error after I put Async function in useEffect


In the useEffect function, if I just mention the getResults function variable, the app doesn't crash. But when I call it as I am doing in code below, I get these errors:

react-dom.development.js:21857 Uncaught TypeError: destroy is not a function

and

Consider adding an error boundary to your tree to customize error handling behavior.

  function App() {
  const [foods, setFoods] = useState([]);
  const [isLoaded, setIsLoaded] = useState(false);
  useEffect(() => getResponse());
  const getResponse = async () => {
    const response = await fetch(sampleRequest);
    const data = await response.json();
    setFoods(data.hits);
  };
  let query = "Tomato";
  let sampleRequest = `https://api.edamam.com/search?q=${query}&app_id=${"1811484f"}&app_key=${"9cac93361efc99e2ebfbb8a453882af8"}`;

  return (
    <div className="App">
      <div className="main">
        <div className="navbars">
          {" "}
          <Navbars></Navbars>
        </div>
        <div className="listings">
          <Listing></Listing>
          <Listing></Listing>
          <Listing></Listing>
          <Listing></Listing>
          <Listing></Listing>
          <Listing></Listing>
          <Listing></Listing>
          <Listing></Listing>
          <Listing></Listing>
          <Listing></Listing>
        </div>
        <div className="footer">
          <h5>Made By YoYo Strangler in 2019</h5>
        </div>
      </div>
    </div>
  );
}

export default App;

Solution

  • You're returning the result of calling getResponse() from the useEffect function. If you return anything from useEffect, it has to be a function. Changing your code to this should fix it because you're no longer returning anything from the useEffect function.

    useEffect(() => { 
      getResponse();
    });
    

    The useEffect Cleanup Function

    If you return anything from the useEffect hook function, it must be a cleanup function. This function will run when the component unmounts. This can be thought of as roughly equivalent to the componentWillUnmount lifecycle method in class components.

    useEffect(() => { 
      doSomething();
    
      return () => {
        console.log("This will be logged on unmount");
      }
    });