Search code examples
graphqlgatsbydirectus

Gatsby 4 dynamic routes with Directus data seems imposible


I'm trying to create dynamic routing. Lets say we are building a blog.

The graphql data i get from Directus looks like this:

{
  Directus {
    Posts {
      id
      slug
      Title
      Body
    }
  }
}

and this seems to be a problem. No matter how i try to create the routes, Gatsby insists that the data structure should be with nodes instead of just an array. I have tried with the "File System Route API" which throws an error because of the missing nodes, the same thing happens if i try to define with "createPages" in gatsby-node.js.

Any help or suggestion is much appreciated...


Solution

  • I got it working... The solution is more simple then any guides i found on google, so here it comes, if anyone else ends up in the same situation.

    Use the old cratePage method in a gatsby-node.js file, in root of project. I used this very simple code:

    const path = require("path")
    
    exports.createPages = async ({ graphql, actions }) => {
      const { data } = await graphql(`
        query Projects {
          Directus {
            Posts {
              slug
            }
          }
        }
      `)
    
      data.Directus.Posts.forEach(post => {
        actions.createPage({
          path: "/blog/" + post.slug,
          component: path.resolve("./src/components/blog.js"),
          context: { slug: post.slug },
        })
      })
    }
    

    And here's a link to useful information: https://www.youtube.com/watch?v=L32Vx_bEZhA