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

150
Visualizações
Initialize state with async function data NextJS?

I'm looking to initialize a state using an asynchronous function:

...
export default function Catalog() {
  const [productsShow, setProductsShow] = useState(getAllProducts())

  ...
  return(
    ... Render products using `productsShow` ... 
  )

getAllProducts()

...
export async function getAllProducts() {

    ...
    return productSet  // Of type Set()
}

The issue I have is the productsShow state is undefined when the page renders. I figure this because the page renders without waiting for the results of the async function to complete. Is there a way to initialize the state with results?

I've tried using the then() function but this results in the same error:

getAllProducts().then(initialProducts => {
    useEffect(() => {
      setProductsShow(preProducts => initialProducts)
    }, [productsShow])
  })

I'm using NextJS

There are some similar questions but differ in technologies used:

  • Initialize state with async data in Redux
  • Can you use an async function to set initial state with useState
about 4 years ago · Juan Pablo Isaza
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