0

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:

engineer-x
  • 2,173
  • 2
  • 12
  • 25
  • 1
    I don't see how the second link fails to provide an answer. Simply initialise with an empty array (`useState([])`) and resolve the products in an effect hook... `useEffect(() => { getAllProducts().then(setProductsShow) }, [])` – Phil Jul 11 '22 at 03:02
  • You might also be interested in Next's [pre-rendering](https://nextjs.org/docs/basic-features/pages#two-forms-of-pre-rendering) capabilities, particularly [static generation with data](https://nextjs.org/docs/basic-features/pages#static-generation-with-data) – Phil Jul 11 '22 at 03:04

0 Answers0