-3

I am connecting to a database, and this query is showing me the IDs that I want:

allSongs {
        edges {
          node {
            id
          }
        }
      }

So now I want to be able to load a dynamic page like this:
site.com/song/6

Where the "6" is the id above. It looks like I'll need to create slugs dynamically based on the query, but I'm having trouble getting it to work. Any help appreciated!

Icaval
  • 29
  • 7
  • 1
    https://www.gatsbyjs.com/docs/tutorial/part-seven/ – xadm Apr 07 '21 at 09:54
  • Yeah, I've read part-seven several times but it's a different scenario that has markdown files in a directory. I'm asking a different question here. – Icaval Apr 07 '21 at 10:06
  • 1
    source can be anything, files/DB/remote CMS, method is the same – xadm Apr 07 '21 at 10:13

1 Answers1

1

You can use createPage api in gatsby-node.js and create dynamic pages

// Create song pages dynamically
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions
  const songTemplate = path.resolve(`src/templates/songs.js`)
  const result = await graphql(`
    query {
      allSongs {
        edges {
          node {
            id
          }
        }
      }
    }
  `)
  result.data.allSongs.edges.forEach(edge => {
    createPage({
      path: `/song/${edge.node.id}`,
      component: songTemplate,
    })
  })
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400