isReady condition satisfies before custom handler is able to fetch the data. What am I missing?
// src/index.js
const topArticleHandler = {
pattern: "top-article-handler",
func: async ({ route, state, libraries }) => {
const handlerResponse = {};
const categoriesId = Object.keys(topArticleCategories);
const allPosts = {};
new Promise((resolve) => {
categoriesId.forEach(async (id) => {
const response = await libraries.source.api.get({
endpoint: `/wp/v2/posts?categories=${id}&per_page=3`,
});
const posts = await response.json();
allPosts[id] = posts;
if (Object.keys(allPosts).length === 3) {
resolve(allPosts);
}
});
}).then((allPosts) => {
new Promise((resolve) => {
categoriesId.forEach(async (id) => {
const categoryData = [];
const categoryPosts = allPosts[id];
categoryPosts.forEach(async (post) => {
const publishDate = post.date_gmt;
const title = post.title.rendered;
const featureMediaResponse = await libraries.source.api.get({
endpoint: `/wp/v2/media/${post.featured_media}`,
});
const featureMediaJSON = await featureMediaResponse.json();
const postSrc = featureMediaJSON.guid.rendered;
let postSrcSet = [];
for (let [key, value] of Object.entries(featureMediaJSON.media_details.sizes)) {
postSrcSet.push([value.source_url, value.width]);
}
const authorResponse = await libraries.source.api.get({
endpoint: `/wp/v2/users/${post.author}`,
});
const authorJSON = await authorResponse.json();
const postAuthor = authorJSON.name;
categoryData.push({
title,
src: postSrc,
date: publishDate,
author: postAuthor,
srcSet: postSrcSet,
category: topArticleCategories[id],
});
if (categoryData.length === 3) {
handlerResponse[id] = categoryData;
if (Object.keys(handlerResponse).length === 3) {
resolve(handlerResponse);
}
}
});
});
}).then((handlerResponse) => {
const data = state.source.get(route);
Object.assign(data, { ...handlerResponse });
});
});
},
};
actions: {
theme: {
beforeSSR: async ({ state, actions }) => {
await actions.source.fetch("top-article-handler");
},
},
},
// topArticle.js
const topArticleData = state.source.get("top-article-handler");
if (topArticleData.isReady){
return <></>
}