LivePreview data was stale if the user entered data while the socket connection was being established. This change ensures fresh data is fetched after the connection is established. This is easy to see when turning on 4G connection and in CI, where it is especially slow.
56 lines
1.3 KiB
TypeScript
56 lines
1.3 KiB
TypeScript
'use client'
|
|
|
|
import type React from 'react'
|
|
|
|
import { isDocumentEvent, ready } from '@payloadcms/live-preview'
|
|
import { useCallback, useEffect, useRef } from 'react'
|
|
|
|
export const RefreshRouteOnSave: React.FC<{
|
|
apiRoute?: string
|
|
depth?: number
|
|
refresh: () => void
|
|
serverURL: string
|
|
}> = (props) => {
|
|
const { apiRoute, depth, refresh, serverURL } = props
|
|
const hasSentReadyMessage = useRef<boolean>(false)
|
|
|
|
const onMessage = useCallback(
|
|
(event: MessageEvent) => {
|
|
if (isDocumentEvent(event, serverURL)) {
|
|
if (typeof refresh === 'function') {
|
|
refresh()
|
|
} else {
|
|
// eslint-disable-next-line no-console
|
|
console.error('You must provide a refresh function to `RefreshRouteOnSave`')
|
|
}
|
|
}
|
|
},
|
|
[refresh, serverURL],
|
|
)
|
|
|
|
useEffect(() => {
|
|
if (typeof window !== 'undefined') {
|
|
window.addEventListener('message', onMessage)
|
|
}
|
|
|
|
if (!hasSentReadyMessage.current) {
|
|
hasSentReadyMessage.current = true
|
|
|
|
ready({
|
|
serverURL,
|
|
})
|
|
|
|
// refresh after the ready message is sent to get the latest data
|
|
refresh()
|
|
}
|
|
|
|
return () => {
|
|
if (typeof window !== 'undefined') {
|
|
window.removeEventListener('message', onMessage)
|
|
}
|
|
}
|
|
}, [serverURL, onMessage, depth, apiRoute, refresh])
|
|
|
|
return null
|
|
}
|