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}
CodePudding user response:
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.