From 65b6a492c3a75a846fbaaf1ab51ad8cd669bf4cf Mon Sep 17 00:00:00 2001 From: satnaing Date: Sun, 18 Aug 2024 01:46:13 +0700 Subject: [PATCH] docs: update estimated reading time blog post async section Update `getStaticPaths` section of `/tags/[tag]/[page].astro` to have resolved promises. Replace `flatMap` with `await Promise.all` and `.flat()`. --- .../how-to-add-an-estimated-reading-time.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/content/blog/how-to-add-an-estimated-reading-time.md b/src/content/blog/how-to-add-an-estimated-reading-time.md index cacdcc3..9ace5f7 100644 --- a/src/content/blog/how-to-add-an-estimated-reading-time.md +++ b/src/content/blog/how-to-add-an-estimated-reading-time.md @@ -228,6 +228,41 @@ const sortedPosts = getSortedPosts(posts); // old code ❌ const sortedPosts = await getSortedPosts(posts); // new code ✅ ``` +Now, `getPostsByTag` function becomes an async function. Therefore, we needs to `await` the `getPostsByTag` function too. + +- src/pages/tags/[tag]/[page].astro +- src/pages/tags/[tag]/index.astro + +```ts +const postsByTag = getPostsByTag(posts, tag); // old code ❌ +const postsByTag = await getPostsByTag(posts, tag); // new code ✅ +``` + +Moreover, update the `getStaticPaths` of `src/pages/tags/[tag]/[page].astro` like this: + +```ts +export async function getStaticPaths() { + const posts = await getCollection("blog"); + + const tags = getUniqueTags(posts); + + // Make sure to await the promises + const paths = await Promise.all( + tags.map(async ({ tag, tagName }) => { + const tagPosts = await getPostsByTag(posts, tag); + const totalPages = getPageNumbers(tagPosts.length); + + return totalPages.map(page => ({ + params: { tag, page: String(page) }, + props: { tag, tagName }, + })); + }) + ); + + return paths.flat(); // Flatten the array of arrays +} +``` + Now you can access `readingTime` in other places besides `PostDetails` ## Displaying reading time (optional)