Subscribe to a Document and Re-Render with React When Updated

3 replies
Last updated: Jul 26, 2022
I wanna make a subscription to a document, and I wanna to react re-render if are any update... How I can do that?
https://www.sanity.io/docs/realtime-updates
is probably a good place to start.

In the example the fetch ends in a console log but it probably makes the most sense for whatever you're rerendering to include the current state of a destructured useState hook and set it inside the same spot the console log is happening.
I read that, but like, I need to update the component right?
When the update hits, you setting the new state triggers the component update, so long as the component contains a reference to the current state.
So if you did


const [ authorName, setAuthorName ] = useState('')
at the start of the component and separately, had a listener going like this (

const subscription = client.listen(query, params)
  .subscribe(update => {
    const comment = update.result
    setAuthorName(comment.author)
  })
and in the JSX returned did something like

<h1>{authorName}</h1>
it should update as the new name got set.

That was just my thought on the pattern. It seems to be corroborated by this repo:
https://github.com/sanity-io/syncing-example/blob/main/src/List.jsx but full disclosure I haven't built anything with the listen endpoint yet.

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?