Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useEffect undefined on first rend

What am i doing wrong here? I’m trying to fetch the data from my API but it keeps returning undefined on my first render, and the next render works fine.

const [data, setData] = useState([])

  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await axios.get("http://localhost:3001/homeFeed")
        
        setData(res.data)
      } catch(err) {
        console.log(err)
      }
    }
    fetchData()
  }, [])

  console.log(data)
// Output: 
// []
// []
// {users: Array(5), id_usuario_logado: 25}
// {users: Array(5), id_usuario_logado: 25}
// {users: Array(5), id_usuario_logado: 25}
// {users: Array(5), id_usuario_logado: 25}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

That’s just how React works. React doesn’t halt rendering until the request inside useEffect resolves.

Usually people either have a state like isLoading set to true at the start then false after the effect finishes, or use a library like tanstack-query (formerly react-query) which handles loading/error state (and more), and while its loading you can either have a loading spinner or display nothing.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading