DEV Community

Phong Duong
Phong Duong

Posted on • Originally published at phongduong.dev on

Create collections from API with Gridsome

Gridsome provides many source plugins that help you create collections from your source. But if you want to create collections from your API or a third-party API, you have to create collections manually.

In gridsome.server.js file, you call loadSource method of api parameter. You pass a callback function which you will fetch the API and create collections from data.

Your callback has an actions parameter, it has addCollection method. You will use this method to create your collections

const axios = require("axios")

module.exports = function(api) {
  api.loadSource(actions) => {
    const { data } = await axios.get('https://example.com/api/v1/posts')
    const postCollection = actions.addCollection("Post")

    for(const post of data) {
      postCollection.addNode({
        id: post.id,
        title: post.title
      })
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

After you start the server, it will create Post collection. To get the collection, you call getCollection method with the collection's name

actions.getCollection("Post")

Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay