birkir / gatsby-source-prismic-graphql

Gatsby source plugin for Prismic GraphQL
MIT License
137 stars 75 forks source link

[Gatsby][Netlify] - Issues implementing previews #175

Open osamaaamer95 opened 4 years ago

osamaaamer95 commented 4 years ago

Context (Environment)

I am trying to integrate previews on a Gatsby blog set up on Netlify. We were using gatsby-source-prismic before. I followed this guide and requested support to enable GraphQL for the repository. We had custom page creation set up from the old plugin, so I removed that code and set up automatic page creation. Relevant code sections are attached.

Expected Behavior

  1. Opening a published article and pressing preview should open the site configured in preview settings with the path '/article/my-published-article. Pressing save on prismic when working on this published article should update the article.
  2. Opening a draft article and pressing preview should open the site configured in prevew settings with the path '/article-preview?uid=my-draft'. Pressing save on prismic when working on this draft article should update the article.

Current Behavior

  1. Opening a published article works. I press on preview in Prismic's dashboard and the page opens up, shows a prismic preview overlay and redirects to the correct article with the correct path. Then I make a change on prismic, and press save. The article refreshes but still shows the old data. I logged the props coming in and they show old data.
  2. Opening a draft article works. I press on preview and the page opens up, showing a prismic preview overlay. I am then redirected to the correct path but the page is blank, with only a toolbar showing on the bottom left corner. Logs show no errors.

Possible Solution

  1. Could it be a caching issue? Logs show the service worker workbox serving data from the cache. I applied the hot reload fix for Gatsby but it does not seem to update the data (refreshes page as expected though).
  2. I have no idea why drafts arent working. I can see the /article-preview page being created during build.

Relevant code

package.json

    "gatsby": "^2.15.21",
    "prismic-reactjs": "^1.3.0",
    "gatsby-source-prismic-graphql": "^3.5.0",

gatsby-config.js

    {
      resolve: 'gatsby-source-prismic-graphql',
      options: {
        repositoryName: 'repo-name',
        defaultLang: 'en-gb',
        accessToken: `${process.env.PRISMIC_API_KEY}`,
        path: '/preview',
        previews: true,
        pages: [
          {
            type: 'Article', // TypeName from prismic
            match: '/article/:uid', // Pages will be generated under this pattern (optional)
            path: '/article-preview', // Placeholder page for unpublished documents
            component: require.resolve('./src/templates/article.js'),
          },
        ],
      },
    },

gatsby-browser.js

import wrapPageElementWithTransition from 'helpers/wrapPageElement';

const { registerLinkResolver } = require('gatsby-source-prismic-graphql');
const { linkResolver } = require('./src/utils/linkResolver');

registerLinkResolver(linkResolver);

export { wrapRootElement } from './src/apollo/wrap-root-element';

import 'typeface-source-serif-pro';
import 'typeface-source-sans-pro';

// Page Transitions
export const wrapPageElement = wrapPageElementWithTransition;

// auto-reload when new content available
export const onServiceWorkerUpdateReady = () => {
  const answer = window.confirm(
    `This application has been updated. ` +
      `Reload to display the latest version?`
  );

  if (answer === true) {
    window.location.reload();
  }
};

linkResolver.js

exports.linkResolver = function linkResolver(doc) {
  // Route for blog posts
  if (doc.type === 'article') {
    return '/article/' + doc.uid;
  }

  // Homepage route fallback
  return '/';
};

article.js

const Post = ({ data: { prismic }, location }) => {
  const doc = prismic.article;
  if (!doc) return null;

  const books = prismic.allChapts.edges.slice(0, 1).pop();
  if (!books) return null;

  // return layout
}

export const pageQuery = graphql`
  query ArticleByUid($uid: String!) {
    prismic {
      allChapts {
        edges {
          node {
            title
            articles {
              article {
                ... on PRISMIC_Article {
                  _meta {
                    uid
                  }
                }
              }
            }
          }
        }
      }
      article(lang: "en-gb", uid: $uid) {
        _meta {
          uid
        }
        title
        meta_title
        meta_description
        subtitle_summary
        draft
        body {
          ... on PRISMIC_ArticleBodyText {
            primary {
              text
              section_anchor
            }
          }
        }
      }
    }
  }
`;

Article.query = pageQuery;
export default Article;

Similar issues

167, #171, #34

leogilmour commented 4 years ago

We're experiencing this exact same issue as documented by @osamaaamer95

osamaaamer95 commented 4 years ago

I created an issue on the community page

jgcmarins commented 4 years ago

Hello everyone, The problem with the preview is working on runtime (after build). A workaround I did was to deploy it into Heroku, running on dev mode.

osamaaamer95 commented 4 years ago

Hello everyone, The problem with the preview is working on runtime (after build). A workaround I did was to deploy it into Heroku, running on dev mode.

@jgcmarins sorry if I misunderstood, but you deployed a dev build on Heroku and previews are now working? Which platform were you using before (if any)?

jgcmarins commented 4 years ago

I am deploying to netlify (the final gatsby build). It works perfectly, but without preview feature. I was able to make preview work only on dev mode, so, the workaround was to the deploy a running instance in dev mode into heroku. Now I have 2 sites running:

  1. the production one, with gatsby build (prismic + netlify)
  2. the preview one, with gatsby develop (prismic + heroku)
osamaaamer95 commented 4 years ago

@jgcmarins did you use an official starter to set up Gatsby? If so, which one? I am trying to get a minimal reproducable repository in order to assess where the issue is.

jgcmarins commented 4 years ago

I used Gatsby Starter Prismic

osamaaamer95 commented 4 years ago

I believe that starter does not use gastby-source-prismic-graphql

jgcmarins commented 4 years ago

Yep, then I refactored it and started using gastby-source-prismic-graphql just because of the preview thing.

MickCoelho commented 4 years ago

Experiencing the exact same problem. Published pages are being correctly previewed, but it doesn't work for unpublished ones. Looks like Gatsby is trying to get the published API (which makes sense), but the data isn't being overwritten by this plugin.

EDIT: If you create a page/article/whatever, publish it and then update it without publishing it, it works as expected.

Duaner commented 4 years ago

Hey guys, we are working on fixing this at the moment on this PR

https://github.com/birkir/gatsby-source-prismic-graphql/pull/150

Duaner commented 4 years ago

Hey, We just released a new version on npm this is an alpha version at the moment that will introduce changes in the configuration.

Let us know if this fixed the issue. ;)

greatwitenorth commented 4 years ago

I upgraded to 3.6.3-alpha.0 and I'm still seeing the issue where the old data persists on my preview page despite clicking save in prismic (this is for a currently published page where I've made updates that have not yet been published). When I look in Chrome's inspector I can see that the new data was indeed fetched under Network, but it never gets hydrated into the page.

I'm also seeing this in my console:

Screenshot 2020-04-30 08 41 51

Unpublished pages just show a blank white page with the purple prismic box in the lower left. I see the same console error from above on these pages as well.

MadsMadsDk commented 4 years ago

I'm also still experiencing problems.

Generally, I think it's a bit unclear how exactly this is supposed to be implemented. I miss a really simple example. None of the examples I've encountered have worked yet.

greatwitenorth commented 4 years ago

@Duaner could we get some clarity on what to do here (even a workaround). Unlike @jgcmarins I cannot even get previews working in develop mode. The lack of previews is currently holding up the development/launch of one of our projects.

damian-tripbuddi commented 4 years ago

I don't know if it is just bad timing. But after seeing Prismic boast some much about the hard work that went into providing Preview support in Gatsby, I moved my stack to Gatsby/Prismic. And now I find out that Preview doesn't work.

I'm not sure if this is a recent regression, or if it has been broken for a long time.

But it's frustrating that there is some much content out their hyping up this as a feature.

I hope that it will either be fixed soon, or the documentation will be updated to say that preview functionality is no longer supported.

MadsMadsDk commented 4 years ago

I've just learned of a potential fix from one of the Prismic-developers. It does work, but you need to be aware of that you MUST name the query exported from your template-components query. So in @osamaaamer95 's case, the article.jsx-component must be

export const query = graphql`...`

and not

export const articleQuery = graphql`...`

The plugin looks to replace the query variable from the component, so we don't have the liberty to name the query whatever we like.

Next problem is, that as soon as you introduce an image to a custom type, the preview breaks again. There's an issue on that right here: #139

I've made an example of previews actually working right here: https://github.com/MadsMadsDk/prismic-preview-i18n-gatsby-test - but be aware, that the Page-component breaks because I've introduced an image. Remove the image, and it works again.

osamaaamer95 commented 4 years ago

Thanks for your comment @MadsMadsDk! I tried renaming it to plain old 'query' when I first investigated the issue but it doesn't work, so it may be the image issue.

I have since moved to Next JS on my current project since this was a major blocker, so I am not actively looking for a solution any more. Hoping to see this fixed soon though ✌️

damian-tripbuddi commented 4 years ago

Thanks @MadsMadsDk for you the information that you provided. By rectifying both of these issues I've now got previews working... it's a shame that I'm going to have to remove the awesomeness of using ImageSharp though. But at least it is now working for my content team to use Previews.

greatwitenorth commented 4 years ago

Looks like my issue ended up being related to https://github.com/birkir/gatsby-source-prismic-graphql/issues/154. I'm at least seeing the updated data now. Still only seeing a blank page for unpublished page previews though.

alexanderfountain commented 4 years ago

Not sure if this will help anyone, but I was having issues while using alias's in my queries. Which you may not need as your queries should all live in "prismic".

greatwitenorth commented 4 years ago

Just to follow up here, I was told by the Prismic staff the following:

We currently don't recommend running projects with Gatsby image or image sharp as these sort of issue arise.

I was then told to use Prismic's built in Imigix solution instead.

It appears as though Prismic has no real plans on properly supporting Gatsby image, one of Gatsby's best features, moving forward. Prismic's built in solution using Imigix (which is what I was told to use) does not allow for a custom domain which means you'll loose all your image SEO value for your domain. They also do not have a full example which shows how to achieve blur up, srcset, lazy loading and other useful features using Gatsby, Prismic and Imigix.

In terms of the pull request that partially fixes previews, it does appear to cause another issue where navigating to another page. The initially previewed page shows up fine, but clicking on link in the previewed page causes the page to show up blank for me.

Duaner commented 4 years ago

Hey,

I think you can have a look at https://github.com/imgix/react-imgix#lazy-loading

And this component should do most of the things that you're looking for. I will see if I find some time to find a provide an example.

If you really want to make it work with gatsby images I will recommend doing a Pull request to fix this problem.

MarcMcIntosh commented 4 years ago

Is Page supposed to be called Article?

Do you have a example project with this issue?

lucashfreitas commented 4 years ago

First of all, I would like to acknowledge the great work that @birkir and all the contributors have done with this awesome plugin.

Second, is there any way that our community can get together to try to find a workaround for this? We can create a discord channel or something like this, I know we are super busy at the moment, but assuming that the preview feature is pretty key for anyone that is developing websites for clients, it might worth a try.

I've read all documentation provided by prismic and this plugin, but it sounds impossible to get the preview working. In my case, I have already removed all gatsby-image (this is another issue that I already know about) and we have other several issues like it doesn't work with fragments, etc, etc. There are definitely some issues that need to be addressed.

The main reason why I choose prismic and gatsby was the possibility to preview content. My website is ready at the moment and it's impossible for my client to preview content, they will have to build every time they wish to do some changes, and it's so frustrating. Unfortunately, I didn't check that before starting the project, otherwise, I would definitely go for another solution as the preview feature is pretty key for the most part of people who develop websites for clients.

Prismic promotes that preview feature works well with gatsby, but actually it doesn't work 100% and it's leading some people like me on making the wrong decision about whether they should use prismic with gatsby, assuming that preview feature works fine:

Prismic community seems to be very helpful, what if we all get together to try to find a way to solve this issue? I am available a few hours a week and super keen to help with that.

Did someone manage to get the preview 100% functional? Even though without gatsby-image?

Some related links:

Common Problems I've found:

image

I would love to see your thoughts and ideas around this!