
We have recently developed a site into the gatsby.
We have a blog site and hosted it on a different domain but now we want to move to one place at our main site. now, we have challenges for displaying dynamic blogs on the gatsby site.
Finally, I found that gatsby provides support to render dynamic blogs as a static page. when build created that time fetch the blogs from the server and create a static page for all the blogs.
Gatsby is a very good platform and manages such a kind of thing easily.
So, I will show you how to create static pages from the API response into the Gatsby site.
Here are the steps you need to follow correctly.
Steps 1
Create a one blog file where you want to load a blog in your design.
For an ex. I created a file `blog/index.js` inside the component directory and the code looks like this,
Steps 2
Open a file `gatsby-node.js`
Declare the const for the API URL at the beginning of the file.
const blogURL = 'http://blog-api.com/api/posts';We need to create an instance of the `node-fetch` for fetching a data from API server.
const fetch = require(`node-fetch`);
Import the path for a resolve the page while creating a static page.
const path = require('path');
See the example how to create a static page from APIs. code look's like,
exports.createPages = (async ({graphql, actions}) => { const blogs = await fetch(blogURL); blogs.data.forEach((blog) => { createPage({ path: 'blog/' + blog.slug, component: path.resolve(`./src/components/blog/index.js`), context: { // Data passed to context is available // in page queries as GraphQL variables. slug: blog.slug, blog: blog, }, }) })
Now we are done, and you can access blogpage via slug.