Created
November 10, 2021 16:02
-
-
Save dayhaysoos/9a1cab127c8c27cbdd71fad518d2a4af to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect } from "react"; | |
type PreviewProviderConfig = { | |
repoName: string; | |
children: React.ReactChild[] | React.ReactChild; | |
}; | |
// TODO: removeEventListener for when component unmounts | |
// TODO: No need for this to be a Provider, make it a component | |
export function PrismicPreview({ repoName, children }: PreviewProviderConfig) { | |
useEffect(() => { | |
if (window) { | |
window.addEventListener("prismicPreviewUpdate", async (event: Event) => { | |
// Prevent the toolbar from reloading the page. | |
event.preventDefault(); | |
const detail = (event as CustomEvent<{ ref: string }>).detail; | |
// Update the preview cookie. | |
await fetch(`/api/preview?token=${detail.ref}`); | |
// Reload the page with the updated token. | |
window.location.reload(); | |
}); | |
} | |
if (window) { | |
window.addEventListener("prismicPreviewEnd", async (event: Event) => { | |
fetch("/api/exit-preview"); | |
}); | |
} | |
}); | |
return ( | |
<React.Fragment> | |
<script | |
async | |
defer | |
src={`https://static.cdn.prismic.io/prismic.js?new=true&repo=${repoName}`} | |
></script> | |
{children} | |
</React.Fragment> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment