I'm working on a project of mines which I started from a free template from the Gatsby site. I wanted to create a blog section in it, nothing too complicated, so I kind of tried to copy what was already there but it doesn't work as I would, I'm creating three different context for three different pages and It's kind of hard to understand, in fact the index page of the blog sometimes has wrong queries showing. I'm pretty sure I'm not that master of Javascript promises, can somebody help? if you do I will much appreciate, have a look at this code
const path = require(`path`);
const { createFilePath } = require(`gatsby-source-filesystem`);
exports.createPages = ({ graphql, actions }) => {
const { createPage } = actions;
return new Promise((resolve, reject) => {
graphql(`
{
allDatoCmsWork {
edges {
node {
slug
}
}
}
allDatoCmsBlog {
edges {
node {
slug
article
title
date
category
}
}
}
}
`).then((result) => {
result.data.allDatoCmsWork.edges.map(({ node: work }) => {
createPage({
path: `works/${work.slug}`,
component: path.resolve(`./src/templates/work.js`),
context: {
slug: work.slug,
},
});
});
result.data.allDatoCmsBlog.edges.map(({ node }) => {
createPage({
path: `blog/${node.slug}`,
component: path.resolve(`./src/templates/article.js`),
context: {
slug: node.slug,
},
});
createPage({
path: `blog/${node.category}`,
component: path.resolve(`./src/templates/gather-category.js`),
context: {
category: node.category
}
});
});
resolve();
});
});
};
Try:
exports.createPages = async ({ graphql, actions }) => {
const result = await graphql(`
{
allDatoCmsWork {
edges {
node {
slug
}
}
}
allDatoCmsBlog {
edges {
node {
slug
article
title
date
category
}
}
}
}
`)
.then((result) => {
result.data.allDatoCmsWork.edges.map(({ node: work }) => {
createPage({
path: `works/${work.slug}`,
component: path.resolve(`./src/templates/work.js`),
context: {
slug: work.slug,
},
});
});
result.data.allDatoCmsBlog.edges.map(({ node }) => {
createPage({
path: `blog/${node.slug}`,
component: path.resolve(`./src/templates/article.js`),
context: {
slug: node.slug,
},
});
createPage({
path: `blog/${node.category}`,
component: path.resolve(`./src/templates/gather-category.js`),
context: {
category: node.category
}
});
});
});
};
Note the promise-based approach with async
and await
functions because graphql
function calls returns a Promise. See: MDN docs more info.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.