-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
3
  • That is because you returned data from useEffect(in 1st example) Commented Jan 7, 2023 at 16:00
  • Welcome to Stack Overflow! Please have a look around and read through the help center, in particular How do I ask a good question? If you meant to answer your own question, please see this help topic for how you would do that. Commented Jan 7, 2023 at 16:02
  • But please search thoroughly before posting. More about searching here. Commented Jan 7, 2023 at 16:06

1 Answer 1

-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.

Sign up to request clarification or add additional context in comments.

2 Comments

"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 I know that. I was talking about the fetchData function declaration inside use effect callback. Thanks for the hint anyways!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.