1
1
import Contentstack from "contentstack"
2
2
import { useEffect , useState } from "react" ;
3
+ import { onEntryChange } from "./api/utils" ;
3
4
4
- let apiUrl = `https://api.contentstack.io/v3/content_types/ashwini_live_preview/entries/blt8a69169a533e195a?`
5
+
6
+ // let apiUrl = `https://api.contentstack.io/v3/content_types/ashwini_live_preview/entries/blt8a69169a533e195a?`
5
7
const Stack = Contentstack . Stack (
6
8
{
7
9
api_key : process . env . api_key ,
@@ -10,6 +12,7 @@ const Stack = Contentstack.Stack(
10
12
}
11
13
) ;
12
14
15
+
13
16
function fetchData ( contentType , entryId ) {
14
17
try {
15
18
if ( entryId ) {
@@ -37,49 +40,20 @@ function fetchData (contentType, entryId){
37
40
38
41
export default function Home ( props ) {
39
42
console . log ( "PROPS" , props )
40
- const [ entry , setEntry ] = useState ( props [ 'single_line' ] )
41
- // const {title, single_line, multi_line, paragraph_1, paragraph_2, paragraph_3, file} = entry
43
+ const [ entry , setEntry ] = useState ( props )
44
+
45
+ const updatedData = async ( ) => {
46
+ let updatedEntry = await fetchData ( "ashwini_live_preview" , "blt8a69169a533e195a" )
47
+ setEntry ( updatedEntry )
48
+ }
42
49
43
50
useEffect ( ( ) => {
44
- //initializing live preview when the page renders for the first time.
45
- window . parent . postMessage (
46
- {
47
- from : "live-preview" ,
48
- type : "init" ,
49
- data : {
50
- config : {
51
- shouldReload : false ,
52
- href : window . location . href ,
53
- } ,
54
- } ,
55
- } ,
56
- "*"
57
- ) ;
58
- //listening to post messages for the hash value
59
- window . addEventListener ( "message" , async ( e ) => {
60
- console . log ( "Event:" , e )
61
- const { data, from, type} = e . data
62
- //check for change in data
63
- if ( data ?. hasOwnProperty ( 'hash' ) && from === "live-preview" && type === "client-data-send" ) {
64
- //making an api call with the hash generated and content type uid
65
- let res = await fetch ( `${ apiUrl } live_preview=${ data [ 'hash' ] } &content_type_uid=${ data [ 'content_type_uid' ] } ` , {
66
- headers : {
67
- api_key : process . env . api_key ,
68
- access_token : process . env . delivery_token
69
- }
70
- } )
71
- let entryData = await res . json ( )
72
- console . log ( "Fetching changed data" , entryData )
73
- //changing the states based on the data changed for that particular hash and rendering the same
74
- if ( entryData ) {
75
- setEntry ( entryData . entry )
76
- }
77
- }
78
- } ) ;
51
+ onEntryChange ( updatedData )
79
52
} , [ ] )
53
+ console . log ( "updated entry" , entry )
80
54
return (
81
55
< div >
82
- < h1 > { entry } </ h1 >
56
+ < h1 > { "HELLO WORLD" } </ h1 >
83
57
</ div >
84
58
)
85
59
}
0 commit comments