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

171
Visualizações
React, fetch data from database before rendering component

I have problems with useState and useEffect. Here is the code:

const [words, setWords] = useState()

useEffect(() => {
    getAllData()
  }, [])

async function getAllData(category){

    let url = `http://127.0.0.1:3000/api/improve-language`

    let response = await fetch(url)
    let data = await response.json()
    let result = await data

    await setWords(result)
  }

I expect from useEffect to get data from api and set to useState variable. And then I'm going to use that useState variable anyway. But, when the website load, I see that useState variable is null, after when I writing a new code line and saving the file, then I see that useState variable has the data finally.

I need to get the data before the website rendering procces. I need to have the data when the page loads. Otherwise, I'm getting errors.

Update: Thanks to everyone who answered to question. Everyone says "use a loader" but I'm already using it. But the main problem is not this.

There are lots of functions and useState variables. And I need the data immediately to make other functions and useState variables to useable.

I'm aldreay using loading effect, but the main problem is functions needs words variable which works for make datas to useable and to present to user.

I need that data after using the setWords(data) function which is in getAllData() function.

I need datas before everything.

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

0

Rather then creating a async function inside the functional hook, you can create a function inside useEffect which gets called on component mount and display a loading spinner when data is being fetched. This is my approach for the above problem statement

const LoadingDiv = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
`

const [words, setWords] = useState()

useEffect(() => {
  const getAllData = async() => {
    let url = `http://127.0.0.1:3000/api/improve-language`;
    let response = await fetch(url)
    let data = await response.json()
    setWords(data)
  };
  getAllData();
}, [])

return (
  words ?
  <YourComponents.../> : <LoadingDiv > Loading... < /LoadingDiv>
);
about 4 years ago · Juan Pablo Isaza Relatório

0

First, you are using more await than it is needed. That has been said, you can use some loading component while you are fetching the data (it is the recommended way), like so :

const [words, setWords] = useState()

useEffect(() => {
    getAllData()
  }, [])

async function getAllData(category){

    let url = `http://127.0.0.1:3000/api/improve-language`

    let response = await fetch(url)
    let data = await response.json()
    setWords(data)
  }
  
  if(!words){
    return <p>Loadin ...</p>
  }
  
about 4 years ago · Juan Pablo Isaza Relatório

0

I think the easiest way is that you would display a loading spinner until you have data in words. That way, the page will load, your spinner will show until theres data, then when data is in you can remove the spinner and actually display your content

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