TracksMastering content operationsCoursesBuild content apps with Sanity App SDKuseDocumentEvent
Build content apps with Sanity App SDK

useDocumentEvent

Log in to watch a video walkthrough of this lesson
Log in
Video thumbnail
Listen to changes to content in your application and trigger events in the user interface.
Log in to mark your progress for each Lesson and Task

User feedback is extremely important in our applications. Especially when users are taking actions as significant as publishing or deleting documents.

Sanity UI comes with hooks to pop up toast notifications. We'll configure that when events happen in this lesson.

Sanity UI exports a ToastProvider which should already be included inside the SanityUI component.

Confirm SanityUI.tsx includes the ToastProvider
import {ThemeProvider, ToastProvider} from '@sanity/ui'
import {buildTheme} from '@sanity/ui/theme'
import {createGlobalStyle} from 'styled-components'
const theme = buildTheme()
const GlobalStyle = createGlobalStyle`
html, body {
margin: 0;
padding: 0;
}
`
export function SanityUI({children}: {children: React.ReactNode}) {
return (
<>
<GlobalStyle />
<ThemeProvider theme={theme}>
<ToastProvider>{children}</ToastProvider>
</ThemeProvider>
</>
)
}

Now you can create a new component to listen to document events as they happen, and when required, pop up toast notifications in the UI.

Create a new FeedbackEvents component to fire toast notifications as events happen
import { DocumentEvent, useDocumentEvent } from "@sanity/sdk-react"
import { useToast } from "@sanity/ui"
export function FeedbackEvents() {
const toast = useToast()
const onEvent = (documentEvent: DocumentEvent) => {
if (documentEvent.type === "published") {
toast.push({
title: "Feedback processed",
status: "success",
})
} else if (documentEvent.type === "deleted") {
toast.push({
title: "Feedback deleted",
status: "error",
})
}
}
useDocumentEvent({ onEvent })
return null
}

This component doesn't render any UI and so can be rendered anywhere inside the SanityApp provider.

Update App.tsx to include the FeedbackEvents component
import { FeedbackEvents } from "./FeedbackEvents"
export function App() {
// ...sanityConfigs, Loading
return (
<SanityUI>
<SanityApp config={sanityConfigs} fallback={<Loading />}>
<Feedback />
<FeedbackEvents />
</SanityApp>
</SanityUI>
)
}
export default App

Now you can click Approve, Mark as Spam or Delete on any document and see a toast notification to show you've completed an action.

At this point, you could consider our app to be "feature complete." Authors are able to set the sentiment of a piece of feedback, add some notes and take a final action on the document.

But we can go deeper!

You have 3 uncompleted tasks in this lesson
0 of 3