Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!