Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
How can i add loading spinner before fetching data in react?

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>
  )
}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda