Creating slugs from graphQL query in Gatsby

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!

Answer

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,
    })
  })
}