Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/admin/hooks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -784,3 +784,33 @@ const MyComponent: React.FC = () => {
</button>
)
}
```

### useDocumentEvents

The `useDocumentEvents` hook provides a way of subscribing to cross-document events, such as updates made to nested documents within a drawer. This hook will report document events that are outside the scope of the document currently being edited. This hook provides the following:

| Property | Description |
|---------------------------|-------------------------------------------------------------------------------------------------------------------------------------------|
| **`mostRecentUpdate`** | An object containing the most recently updated document. It contains the `entitySlug`, `id` (if collection), and `updatedAt` properties |
| **`reportUpdate`** | A method used to report updates to documents. It accepts the same arguments as the `mostRecentUpdate` property. |

**Example:**

```tsx
import { useDocumentEvents } from 'payload/components/utilities'

const ListenForUpdates: React.FC = () => {
const { mostRecentUpdate } = useDocumentEvents()

return (
<span>
{JSON.stringify(mostRecentUpdate)}
</span>
)
}
```

<Banner type="info">
Right now the `useDocumentEvents` hook only tracks recently updated documents, but in the future it will track more document-related events as needed, such as document creation, deletion, etc.
</Banner>
13 changes: 8 additions & 5 deletions packages/payload/src/admin/Root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { StepNavProvider } from './components/elements/StepNav'
import { AuthProvider } from './components/utilities/Auth'
import { ConfigProvider } from './components/utilities/Config'
import { CustomProvider } from './components/utilities/CustomProvider'
import { DocumentEventsProvider } from './components/utilities/DocumentEvents'
import { I18n } from './components/utilities/I18n'
import { LoadingOverlayProvider } from './components/utilities/LoadingOverlay'
import { LocaleProvider } from './components/utilities/Locale'
Expand Down Expand Up @@ -49,11 +50,13 @@ const Root = ({ config: incomingConfig }: { config?: SanitizedConfig }) => {
<LocaleProvider>
<StepNavProvider>
<LoadingOverlayProvider>
<NavProvider>
<CustomProvider>
<Routes />
</CustomProvider>
</NavProvider>
<DocumentEventsProvider>
<NavProvider>
<CustomProvider>
<Routes />
</CustomProvider>
</NavProvider>
</DocumentEventsProvider>
</LoadingOverlayProvider>
</StepNavProvider>
</LocaleProvider>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import React, { createContext, useContext, useState } from 'react'

import type { UpdatedDocument } from './types'

const Context = createContext({
mostRecentUpdate: null,
reportUpdate: (doc: UpdatedDocument) => null, // eslint-disable-line @typescript-eslint/no-unused-vars
})

export const DocumentEventsProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [mostRecentUpdate, reportUpdate] = useState<UpdatedDocument>(null)

return <Context.Provider value={{ mostRecentUpdate, reportUpdate }}>{children}</Context.Provider>
}

export const useDocumentEvents = () => useContext(Context)
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export type UpdatedDocument = {
entitySlug: string
id?: string
updatedAt: string
}

export type DocumentEventsContext = {
mostRecentUpdate: UpdatedDocument
reportUpdate: (updatedDocument: Array<UpdatedDocument>) => void
}
21 changes: 20 additions & 1 deletion packages/payload/src/admin/components/views/Global/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import buildStateFromSchema from '../../forms/Form/buildStateFromSchema'
import { fieldTypes } from '../../forms/field-types'
import { useAuth } from '../../utilities/Auth'
import { useConfig } from '../../utilities/Config'
import { useDocumentEvents } from '../../utilities/DocumentEvents'
import { useDocumentInfo } from '../../utilities/DocumentInfo'
import { EditDepthContext } from '../../utilities/EditDepth'
import { useLocale } from '../../utilities/Locale'
Expand All @@ -37,10 +38,17 @@ const GlobalView: React.FC<IndexProps> = (props) => {
serverURL,
} = useConfig()

const { reportUpdate } = useDocumentEvents()

const { admin: { components: { views: { Edit: Edit } = {} } = {} } = {}, fields, slug } = global

const onSave = useCallback(
async (json) => {
reportUpdate({
entitySlug: global.slug,
updatedAt: json?.result?.updatedAt || new Date().toISOString(),
})

getVersions()
getDocPermissions()
setUpdatedAt(json?.result?.updatedAt)
Expand All @@ -59,7 +67,18 @@ const GlobalView: React.FC<IndexProps> = (props) => {
})
setInitialState(state)
},
[getVersions, fields, user, locale, t, getDocPermissions, getDocPreferences, config],
[
getVersions,
fields,
user,
locale,
t,
getDocPermissions,
getDocPreferences,
config,
global,
reportUpdate,
],
)

const [{ data, isLoading: isLoadingData }] = usePayloadAPI(`${serverURL}${api}/globals/${slug}`, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { DocumentHeader } from '../../../elements/DocumentHeader'
import { FormLoadingOverlayToggle } from '../../../elements/Loading'
import Form from '../../../forms/Form'
import { useAuth } from '../../../utilities/Auth'
import { useDocumentEvents } from '../../../utilities/DocumentEvents'
import { OperationContext } from '../../../utilities/OperationProvider'
import { CollectionRoutes } from './Routes'
import { CustomCollectionComponent } from './Routes/CustomComponent'
Expand Down Expand Up @@ -42,12 +43,19 @@ const DefaultEditView: React.FC<DefaultEditViewProps> = (props) => {
onSave: onSaveFromProps,
} = props

const { reportUpdate } = useDocumentEvents()

const { auth } = collection

const classes = [baseClass, isEditing && `${baseClass}--is-editing`].filter(Boolean).join(' ')

const onSave = useCallback(
async (json) => {
reportUpdate({
id,
entitySlug: collection.slug,
updatedAt: json?.result?.updatedAt || new Date().toISOString(),
})
if (auth && id === user.id) {
await refreshCookieAsync()
}
Expand All @@ -59,7 +67,7 @@ const DefaultEditView: React.FC<DefaultEditViewProps> = (props) => {
})
}
},
[id, onSaveFromProps, auth, user, refreshCookieAsync],
[id, onSaveFromProps, auth, user, refreshCookieAsync, collection, reportUpdate],
)

const operation = isEditing ? 'update' : 'create'
Expand Down