control-panel
control-panel

Reputation: 275

Gatsby overwrite a static page (createPages) with a dynamic one?

We have a user platform project. Every user has a profile detail page (/{id}} we create during build with createPages(). When the user who is logged in makes changes to his profile they will persist in the database, but the changes will not be visible to him until the build is triggered again. The user might think his changes are lost and might get frustrated. Our ideal solution would be to show the profile of the user that is logged in dynamically.

Is it possible to overwrite a static created page with a dynamic page on the same url? We want to keep the url the same (/{id}) because the user will share his link with other users.

// Generation of static pages
exports.createPages = async function ({ actions, graphql }) {
  const { data } = await graphql(`
    query {
      apollo {
        allProfiles {
          email
          id
        }
      }
    }
  `)
  data.apollo.allProfiles.forEach((profile) => {
    const email = profile.email
    const id = profile.id
    actions.createPage({
      path: id,
      component: require.resolve(`./src/templates/profile-detail.js`),
      context: { email: email },
    })
  })
}

Upvotes: 1

Views: 280

Answers (1)

Ferran Buireu
Ferran Buireu

Reputation: 29305

I think there's a misunderstanding of how Gatsby works. Your page is static in terms of content but it's dynamic in terms of JavaScript and React's logic.

Your page currently is static because you populate your component/pages in the build time, however, you need to make an API request (via axios for example) to and endpoint to fetch the changes in your database and populate your React state and show/hide components in your JavaScript logic, not in the server itself.

Your /{id} will remain exactly the same because it's created during the createPage but you will add a logic depending on the user's actions.

Upvotes: 1

Related Questions