I’m fetching WordPress posts asynchronously via getStaticProps()
…
export async function getStaticProps({ params, preview = false, previewData }) {
const data = await getPostsByCategory(params.slug, preview, previewData)
return {
props: {
preview,
posts: data?.posts
},
}
}
… and passing them to useState
:
const [filteredArticles, setFilteredArticles] = useState(posts?.edges)
Then, I pass the state to a component:
router.isFallback ? (
// If we're still fetching data...
<div>Loading…</div>
) : (
<ArticleGrid myArticles={filteredArticles} />
This is necessary because another component will setFilteredArticles
with a filter function.
But when we are passing the state to ArticlesGrid
, the data is not ready when the component loads. This is confusing to me since we passing the state within a router.isFallback
condition.
Even if we set state within useEffect
…
const [filteredArticles, setFilteredArticles] = useState()
useEffect(() => {
setFilteredArticles(posts)
}, [posts?.edges])
… the data arrives too late for the component.
I’m new to Next.js. I can probably hack my way through this, but I assume there’s an elegant solution.