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: