-2

I was trying the useEffect example something like below:

import React , {useState , useEffect} from 'react'
import axios from 'axios'

function Homescreen() {

useEffect(async() => {
  
try {
  const data = (await axios.get('/api/rooms/getallrooms')).data
console.log(data)
return data;

} catch (error) {
  console.log(error)
}

}, [])



  
  return (
    <div>
        <h1>Home Screen</h1>

    </div>
  )
}

export default Homescreen

This is the warning poped up,

It looks like you wrote useEffect(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:

useEffect(() => {
  async function fetchData() {
    // You can await here
    const response = await MyAPI.getData(someId);
    // ...
  }
  fetchData();
}, [someId]); // Or [] if effect doesn't need props or state
Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
AlphaJR09
  • 1
  • 2
  • That is because you returned data from useEffect(in 1st example) – vbykovsky Jan 07 '23 at 16:00
  • Welcome to Stack Overflow! Please have a look around and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) If you meant to answer your own question, please see [this help topic](https://stackoverflow.com/help/self-answer) for how you would do that. – T.J. Crowder Jan 07 '23 at 16:02
  • But please [search thoroughly](/search?q=%5Bjs%5D+useEffect+function+must+return+a+function) before posting. More about searching [here](/help/searching). – T.J. Crowder Jan 07 '23 at 16:06

1 Answers1

-1

When you return something on useEffect is the "unbind" function. You can do this to fix that:

useEffect(async () => {
    const response = await MyAPI.getData(someId);
    // do your stuff here
}, [someId]);

I don't see a reason for declaring a function on use effect and calling it only there.

Felipe Esteves
  • 363
  • 1
  • 10
  • 1
    "*I don't see a reason for declaring a function on use effect and calling it only there.*" the reason is to follow the React hooks rules. `useEffect` hook expects nothing to be returned (`undefined`) or a cleanup function. And your code breaks exactly that (it returns a Promise) and throws a warning. – Aleksandar Jan 07 '23 at 16:18
  • @Aleksandar I know that. I was talking about the fetchData function declaration inside use effect callback. Thanks for the hint anyways! – Felipe Esteves Jan 09 '23 at 13:27