prismicio / prismic-gatsby

Gatsby plugins for building websites using Prismic
https://prismic.io/docs/technologies/gatsby
Apache License 2.0
313 stars 97 forks source link

v3: Support needed – preview-page will not redirect #137

Closed kossowski closed 3 years ago

kossowski commented 5 years ago

Version 3.0.0-beta.10

I build a very simple project to test the preview function with a new prismic repository. Unfortunately, the /preview page opens, but not redirect to the right page. It just shows Loading preview....

The link looks like this: http://localhost:8000/preview?token=https%3A%2F%2F[MY_REPO_NAME]%2Fpreviews%2FXYDiOhEAACgAZCdO%3FwebsitePreviewId%3DXYCURREAACUAYrzj&documentId=XYC-RBEAACUAY3_Z

There are no errors or warnings, that's why I don't know what's going on.

You can find my repo here: https://github.com/kossowski/prismic-preview-demo

It would be great if someone could take a quick look and check what possible went wrong.

angeloashmore commented 5 years ago

@kossowski I'm not able to run your project since it requires your Prismic repo's access token, but my guess is your link resolver is not returning a path.

Your link resolver currently looks like this:

// gatsby-config.js
{
  linkResolver: () => () => {
    linkResolver
  },
}

But based on your src/utils/linkResolver.js, it should be this:

// gatsby-config.js
{
  linkResolver: () => linkResolver,
}

Note that the linkResolver option should be a function of the form:

gatsbyData => doc => {
  // Return a path as a string
}

Where gatsbyData is an object with key, value, and node properties. These can usually be ignored unless you need to change your link resolver function based on that data.

kossowski commented 5 years ago

@angeloashmore Thank you for the fast reply! I understand my mistake on the linkResolver and fixed it. Unfortunately it not resolved the issue. My repo was updated with the access token, so you could run the project. I'm sure it's just a basic logic error, but I dont' get it ...

angeloashmore commented 5 years ago

@kossowski No problem! I’ll give it a try tomorrow to see if I can find what’s going on.

angeloashmore commented 5 years ago

@kossowski I just realized I can't actually test previews without access to the repo since Prismic requires the previewer to be logged in.

Could you share your console output when you try to preview from Prismic? The hook will run a validator on the options passed to the hook. I think you may see validation errors in your console.

My next guess is you need to provide the linkResolver option to the hook. The hook smartly grabs all the plugin options from your gatsby-config.js file, but functions cannot be passed automatically, unfortunately.

{
  repositoryName: 'repoName',
  linkResolver: () => linkResolver,
}

Where plugin options are validated: https://github.com/angeloashmore/gatsby-source-prismic/blob/v3-beta/src/browser/usePrismicPreview.js#L62

The validation schema: https://github.com/angeloashmore/gatsby-source-prismic/blob/v3-beta/src/common/validatePluginOptions.js

Could you also provide the verbose output from gatsby build --verbose? This will print out a bunch of debug information from the plugin.

The docs have gotten a bit out of date since the latest versions so I'll leave this here as a reminder to update them.

kossowski commented 5 years ago

@angeloashmore Okay, so I added { linkResolver: () => linkResolver } into my /preview page-overrides and it redirect correctly now 🎉

The only problem is that the page content will not update. It just shows the published state not the saved state of the prismic document. My guess is there is a error with the mergePrismicPreviewData (?)

The console output was clean the whole time and got no validation errors (before and after this fix).

gatsby build --verbose output before the fix:

➜ gatsby build --verbose
verbose set gatsby_log_level: "verbose"
verbose set gatsby_executing_command: "build"
verbose loading local command from: /Users/denniskossowski/Documents/git/github/prismic-preview-demo/node_modules/gatsby/dist/commands/build.js
verbose running command: build

success open and validate gatsby-configs - 0.022 s
success load plugins - 0.225 s
success onPreInit - 0.014 s
success delete html and css files from previous builds - 0.023 s
success initialize cache - 0.016 s
success copy gatsby files - 0.050 s
success onPreBootstrap - 0.016 s
verbose gatsby-source-prismic - starting to create types
success gatsby-source-prismic - create types - 0.018 s
verbose gatsby-source-prismic - starting to fetch documents
verbose gatsby-source-prismic - fetching documents page 1
verbose gatsby-source-prismic - fetched 2 documents
success gatsby-source-prismic - fetch documents - 0.836 s
verbose gatsby-source-prismic - starting to create nodes
verbose gatsby-source-prismic - creating node {"id":"08d0dc02-40e0-51ea-b4c2-48f922155591","type":"PrismicBlog","prismicId":"XYC-RBEAACUAY3_Z"}
verbose gatsby-source-prismic - creating node {"id":"ab3a3a28-0e83-575d-868c-0db4935958c4","type":"PrismicHomepage","prismicId":"XYCSJxEAACgAYrMy"}
success gatsby-source-prismic - create nodes - 0.039 s
verbose gatsby-source-prismic - starting to write out type paths
verbose gatsby-source-prismic - writing out type paths to:
/Users/denniskossowski/Documents/git/github/prismic-preview-demo/public/undefined8dbfd1a81a0b88cd4c43f251a93f4a5c.json
success gatsby-source-prismic - write out type paths - 0.019 s
success source and transform nodes - 1.010 s
success Add explicit types - 0.021 s
warn Deprecation warning - adding inferred resolver for field PrismicBlog.first_publication_date. In Gatsby v3, only fields with an explicit directive/extension
will get a resolver.
warn Deprecation warning - adding inferred resolver for field PrismicBlog.last_publication_date. In Gatsby v3, only fields with an explicit directive/extension
will get a resolver.
warn Deprecation warning - adding inferred resolver for field PrismicHomepage.first_publication_date. In Gatsby v3, only fields with an explicit
directive/extension will get a resolver.
warn Deprecation warning - adding inferred resolver for field PrismicHomepage.last_publication_date. In Gatsby v3, only fields with an explicit
directive/extension will get a resolver.
success Add inferred types - 0.151 s
success Processing types - 0.073 s
success building schema - 0.303 s
success createPages - 0.030 s
success createPagesStatefully - 0.044 s
success onPreExtractQueries - 0.011 s
success update schema - 0.028 s
success extract queries from components - 0.095 s
success write out requires - 0.015 s
success write out redirect data - 0.012 s
success onPostBootstrap - 0.010 s
⠀
info bootstrap finished - 4.669 s
⠀
success run static queries - 0.011 s
success Building production JavaScript and CSS bundles - 10.643 s
success Rewriting compilation hashes - 0.065 s
success run page queries - 0.021 s — 1/1 281.81 queries/second
success Building static HTML for pages - 1.080 s — 3/3 16.83 pages/second
info Done building in 16.571433688 sec
pr1ntr commented 5 years ago

Dose this plugin require a UID? I have pages that do not require a uid (eg the home page). It seems that when I try to preview pages that do no have uid i get this error:

index.esm.js:205 Uncaught (in promise) TypeError: Cannot read property 'type' of undefined
    at _callee7$ (index.esm.js:205)
    at tryCatch (runtime.js:45)
    at Generator.invoke [as _invoke] (runtime.js:271)
    at Generator.prototype.<computed> [as next] (runtime.js:97)
    at asyncGeneratorStep (asyncToGenerator.js:3)
    at _next (asyncToGenerator.js:25)
    at asyncToGenerator.js:32
    at new Promise (<anonymous>)
    at asyncToGenerator.js:21
    at documentToNodes (index.esm.js:205)
    at _callee9$ (index.esm.js:293)
    at tryCatch (runtime.js:45)
    at Generator.invoke [as _invoke] (runtime.js:271)
    at Generator.prototype.<computed> [as next] (runtime.js:97)
    at asyncGeneratorStep (asyncToGenerator.js:3)
    at _next (asyncToGenerator.js:25)
...

This is the code to my preview page:

import PropTypes from 'prop-types'
import { rem } from 'polished'
import { usePrismicPreview } from 'gatsby-source-prismic'
import { navigate } from 'gatsby'
import { PRISMIC_REPO_NAME } from '../../../lib/constants'
import getPath from '../../../lib/getPath'
import { get } from 'lodash'
import Page from '../container/Page'
import Text from '../common/Text'
import { Row, Col } from 'react-flexa'
import Loader from 'react-loader-spinner'
import 'react-loader-spinner/dist/loader/css/react-spinner-loader.css'

import styled from 'styled-components'
import theme from '../../style/theme'
import useParseSiteData from '../../hooks/useParseSiteData'

const PreviewPage = ({ location, pageContext: { pages, staticData: data } }) => {
  const pageUIDs = pages.map(getPath)

  const { sections } = useParseSiteData(data)

  const pathResolver = () => doc => {
    const previewSlug = getPath(doc)
    if (pageUIDs.includes(previewSlug)) {
      return previewSlug
    } else {
      return '/draft'
    }
  }
  const { previewData, path } = usePrismicPreview(location, {
    repositoryName: PRISMIC_REPO_NAME,
    pathResolver,
  })

  useEffect(() => {
    if (previewData && path) {

      const keys = Object.keys(previewData)
      const key = keys.length ? keys[0] : false

      window.__PRISMIC_PREVIEW_DATA__ = key ? previewData[key] : previewData
      navigate(path)
    }
  }, [previewData, path])

  return  <Page {...sections}>
    <PreviewRow justifyContent="center" alignContent="center" alignItems="center" direction="column">
      <StyledLoader
        type="Oval"
        color={theme.color.blue}
        height={200}
        width={200}
      />
      <Col xs={12}>
        <LoadPreviewText center xs={22} md={32}  lg={32} xxl={32}>Loading Preview...</LoadPreviewText>
      </Col>
    </PreviewRow>
  </Page>
}

PreviewPage.propTypes = {
  location: PropTypes.object,
  pageContext: PropTypes.object,
}

export default PreviewPage

const LoadPreviewText = styled(Text.h1)`

`

const PreviewRow = styled(Row)`
  height: 100%;
`

const StyledLoader = styled(Loader)`
  margin-bottom: ${rem(50)};
`

Chrome Debugger is making it very difficult to step through the sourcemaps for some reason all the breakpoints are grayed out.

Anyway the only observable difference at this point is just not having a uid.

The preview page has that pathResolver but the plugin config has this linkResolver:

linkResolver: ({ node }) => entry => {
          if (PAGE_TYPES.includes(node.type) && entry.id === node.id) {
            const path = node.data.path ? getPath(node) : '/'
            return path
          } else {
            return null
          }
        },

So here my use case is that pages need a path field which tells gatsby where the page is. I am not really sure how else to do this, basically anytime entry matches node i add an entry to whatever array linkResolver feeds into.

Another strange thing is that when it tries to look for the page to preview it seems to be making multiple calls to the prismic api, as if it wants to get other pages. it makes 4 of these calls:

https://rushstreet-dev.cdn.prismic.io/api/v2?access_token=<TOKEN>

All return the right data for the master ref. Then it proceeds to to make queries for other pages and get data. Except there is one query that has no results and when I go back to check the ID in the api explorer that ID doesn't even exist.

https://rushstreet-dev.cdn.prismic.io/api/v2/documents/search?page=1&pageSize=1&access_token=<TOKEN>&fetchLinks=&lang=*&ref=https://rushstreet-dev.prismic.io/previews/XY6M4xEAACAAXmb9?websitePreviewId=XSfd0RIAACAAHG2D&q=[[at(document.id, "XSjR7xIAAB8AIJvk")]]

So in this case i have no idea what "XSjR7xIAAB8AIJvk" is referring to. It's not the id of the page I am actually looking for.

Any insight helps. Thanks.

pr1ntr commented 4 years ago

@angeloashmore I have been racking my brain on this quite a bit and I made some headway. After digging around the source I found the culprit here.

I am able to fix it checking for value.type !== 'broken_type'

PR #168

angeloashmore commented 3 years ago

I'm cleaning out old issues and closing this due to its age. If this is still a problem, please open a new issue and I will take a look!