What is the correct way to add a spinner while fetching data from API in react js? I tried to display the spinner until the data.length > 0 it works fine when the data is more than zero. But when it is actually zero, the loading spinner doesn't stop. Is there any good solution for this?
You didn't provide enough info or code to tell exactly what to do but i will give you a simple example
just create a state for the loading set it true and when the fetch is done set it false
I hope this example is clear
import { useEffect,useState } from 'react'
export default function Page() {
const [data, setData] = useState(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
fetch('/api/test',{method: 'GET'})
.then(res => res.json())
.then(data => {
console.log(data)
setData(data)
}
)
.catch(err => {
console.log(err)
}
)
.finally(() => {
setLoading(false)
})
}, [])
if(loading) return <div>Loading...</div> // or your loading spinner
return (
<div>{JSON.stringify(data)}</div>
)
}